Search Results

Search found 4088 results on 164 pages for 'params keyword'.

Page 44/164 | < Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >

  • Linq-to-Sql query advice please

    - by Mantorok
    Hi all Just wondering if this is a good approach, I need to search for items containing all of the specified keywords in a space-delimted string, is this the right approach this? var result = (from row in DataContext.PublishedEvents join link in DataContext.PublishedEvent_EventDateTimes on row.guid equals link.container join time in DataContext.EventDateTimes on link.item equals time.guid orderby row.EventName select new {row, time}); // Split the keyword(s) to limit results with all of those words in. foreach(var keyword in request.Title.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { var val = keyword; result = result.Where(row=>row.row.EventName.Contains(val)); } var end = result.Select(row=>new EventDetails { Title = row.row.EventName, Description = TrimDescription(row.row.Description), StartDate = row.time.StartDate, EndDate = row.time.EndDate, Url = string.Format(ConfigurationManager.AppSettings["EventUrl"], row.row.guid) }); response.Total = end.Count(); response.Result = end.ToArray(); Is there a slick Linq-way of doing all of this in one query? Thanks

    Read the article

  • Formatting Log File Messages

    - by Kumar
    This is about formatting the messages for logging so as to subsequently be able to parse them relatively easily esp. given the extensive logging required in financial apps Typically a line in the log file is of the form TimeStamp: Module/Function: where the log string contains whatever you choose, typically you'd have some key=value paradigm or even johnny5 key {value} etc. A regex search through the log file might easily pick up Module/Function but enforcing and maintaing consistency on the log string itself for every developer on the team is often a pain The logging api's are typically ILog.LogInfo(string text, params object[] args) ILog.LogWarning(string text, params object[] args) ILog.LogError(string text, params object[] args) Looking for opinions on better logging api's to format the log messages where a regex search can be performed for Module/Function = Basket/AddItem TokenA = Value1 and TokenB = Value2 etc. without going over every developer's every logging call

    Read the article

  • Loop throught form inputs

    - by Victor
    I have a form with lots of inputs. I want to get each id and value and then put them in $.load method. I tried this: $("#form input").each(function() { var name = $(this).attr("id"); var value = $(this).attr("value"); $.extend(params, { name, value }); }); and then use $.load("script.php", params); But obviously it doesn't work. In params I have only one element "name". And I'm not sure I should use extend method too.

    Read the article

  • Rendering another Action without changing URL?

    - by Michael Stum
    I have this code in my Rails 3 controller: def index now = Time.now.utc.strftime("%m%d") redirect_to :action => "show", :id => now end def show begin @date = Time.parse("12#{params[:id]}") dbdate = params[:id] rescue ArgumentError @date = Time.now.utc dbdate = @date.strftime("%m%d") end @date = @date.strftime("%B %d") @events = Event.events_for_date(dbdate) end So basically index is just a specialized version of show, hence I want it to execute show, render the show.html.erb view - but I do not want to change the URL like redirect_to does. I have tried this approach: def index now = Time.now.utc.strftime("%m%d") params[:id] = now show render :action => "show" end Now, this works, but it just smells badly. I'm new to Ruby and Rails, so I just wonder if there is something fundamentally wrong or if there is a better way to do this?

    Read the article

  • How to change Zend_Db_Table name within a Model to insert in multiple tables

    - by jwhat
    Using Zend Framework, I've created a Model to insert a record into a database. My question is, after $this->insert($data) how can I switch the active table so that I can insert a record into another table? Here's my code so far: class Model_DbTable_Foo extends Zend_Db_Table_Abstract { protected $_name = 'foo'; public function addFoo($params) { $data = array( 'foo' => $params['foo'], ); $this->insert($data); $foo_id = $this->getAdapter()->lastInsertId(); $data2 = array( 'bar' => $params['bar'] ); // I need to change the Db Table name here. $this->insert($data2); $bar_id = $this->getAdapter()->lastInsertId(); } }

    Read the article

  • Perl CGI script to not wait for a subprocess to complete

    - by Tyug
    Is it possible to continue displaying a CGI script's HTML without waiting for a child process to complete, yet the child process should stay alive when the CGI script is complete. Here's what I have, -- Display HTML page # html page set up... so header/other stuff #the -c, -h are params are just params system("perl subprocess.pm -c params -h 1 &"); #actually print the html page setup ... For some weird reason, it waits for the subprocess to finish before it outputs the html page even though I included the asynchronous system call for linux. It doesn't render the page immediately. Is it possible to print the html page without waiting for the subprocess to finish?

    Read the article

  • Using eval() in Javascript to unpack the array

    - by gnomixa
    I have an array that I need to unpack. So, from something like var params = new Array(); params.push("var1"); params.push("var2"); I need to have something like "var1", "var2". I tried using eval, but eval() gives me something like var1, var2...i don't want to insert quotes myself as the vars passed can be integers, or other types. I need to pass this to a function, so that's why i can't just traverse the array and shove it into a string. What is the preferred solution here?

    Read the article

  • js regexp problem

    - by Alexander
    I have a searching system that splits the keyword into chunks and searches for it in a string like this: var regexp_school = new RegExp("(?=.*" + split_keywords[0] + ")(?=.*" + split_keywords[1] + ")(?=.*" + split_keywords[2] + ").*", "i"); I would like to modify this so that so that I would only search for it in the beginning of the words. For example if the string is: "Bbe be eb ebb beb" And the keyword is: "be eb" Then I want only these to hit "be ebb eb" In other words I want to combine the above regexp with this one: var regexp_school = new RegExp("^" + split_keywords[0], "i"); But I'm not sure how the syntax would look like. I'm also using the split fuction to split the keywords, but I dont want to set a length since I dont know how many words there are in the keyword string. split_keywords = school_keyword.split(" ", 3); If I leave the 3 out, will it have dynamic lenght or just lenght of 1? I tried doing a alert(split_keywords.lenght); But didnt get a desired response

    Read the article

  • Asynchrous calls cause StaleObjectStateException

    - by Mulone
    Hi all, I'm struggling with a Grails service. The service gets AJAX calls from the clients and behaves like a simple local cache for remote objects: void **someCallFromClient**() { // extract params def results = remoteService.queryService(params) results.each{ // try to fetch result object from local DB def obj = SomeClass.findBySomeField(result.someField) if (!obj){ obj = new Result(params) obj.save() } // do stuff on obj } } The service works fine when only one client is connected, but as soon as 2 or more clients start bombing the server with requests, I start getting: 2010-05-24 13:09:49,764 [30893094@qtp-26315919-2] ERROR errors.GrailsExceptionResolver - Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [ some object #892901] org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [ some object #892901] // very long stactrace It probably happens when 2 calls are trying to create the same object concurrently. I suppose this is a rather typical situation to end up in. Could you recommend any pattern/good practice to fix this issue? For example, is there a way to say to one of the service instances to hang on and wait for the other to finish its stuff and try again? Cheers!

    Read the article

  • Separating an Array into a comma seperated string with quotes

    - by user548744
    I'm manually building an SQL query where I'm using an Array in the params hash for an SQL IN statement, like: ("WHERE my_field IN('blue','green','red')"). So I need to take the contents of the array and output them into a string where each element is single quoted and comma seperated (and with no ending comma). So if the array was: my_array = ['blue','green','red'] I'd need a string that looked like: "'blue','green','red'" I'm pretty new to Ruby/Rails but came up with something that worked: if !params[:colors].nil? @categories_array = params[:colors][:categories] @categories_string ="" for x in @categories_array @categories_string += "'" + x + "'," end @categories_string.chop! #remove the last comma end So, I'm good but curious as to what a proper and more consise way of doing this would look like? Thanks

    Read the article

  • Too Few Arguments

    - by NoahClark
    I am trying to get some Javascript working in my Rails app. I want to have my index page allow me to edit individual items on the index page, and then reload the index page upon edit. My index.html.erb page looks like: <div id="index"> <%= render 'index' %> </div> In my index.js.erb I have: $('#index').html("<%=j render 'index' %>"); and in my holders_controller: def edit holder = Holder.find(params[:id]) end def update @holder = Holder.find(params[:id]) if @holder.update_attributes(params[:holder]) format.html { redirect_to holders_path } #, flash[:success] = "holder updated") ## ^---Line 28 in error format.js else render 'edit' end end When I load the index page it is fine. As soon as click the edit button and it submits the form, I get the following: But if I go back and refresh the index page, the edits are saved. What am I doing wrong?

    Read the article

  • How do I dynamically assign the Model for a .find in Ruby on Rails?

    - by Angela
    I am trying to create a Single Table Inheritance. However, the Controller must be able to know which class to find or create. These are based on another class. For example, ContactEvent with type = Letter needs to grab attributes from a corresponding Model called Letter. Here's what I've tried to do and hit a snag, labelled below. I need to be able to dynamically call assign a value of EventClass so that it can be Letter.find(:conditions =) or Calls.find(:conditions =) depending on which type the controller is acting on. def new @contact_event = ContactEvent.new @contact_event.type = params[:event_type] # can be letter, call, postcard, email @contact_event.event_id = params[:event_id] # that ID to the corresponding Model @contact_event.contact_id = params[:contact] @EventClass = case when @contact_event.type == 'letter' then 'Letter' when @contact_event.type == 'call' then 'Call' when @contact_event.type == 'email' then 'Email' SNAG BELOW: @event = @EventClass.find(@contact_letter.letter_id) #how do I make @EventClass actually the Class?SNAG # substitution of variables into the body of the contact_event @event.body.gsub!("{FirstName}", @contact.first_name) @event.body.gsub!("{Company}", @contact.company_name) @evebt.body.gsub!("{Colleagues}", @colleagues.to_sentence) @contact_event.body = @event.body @contact_event.status = "sent" end

    Read the article

  • How to use string interpolation when rendering templates?

    - by Senthil
    I found this code in a Rails cookbook. class BlogController < ApplicationController def display_by_date year = params[:year] month = params[:month] day = params[:day] day ='0'+day if day && day.size == 1 @day = day if ( year && month && day ) render(:template => "blog/#{year}/#{month}/#{day}") elsif ( year ) render(:template => "blog/#{year}/list") end end end I'm not sure what to name the templates so the router can find them. Thanks for your help.

    Read the article

  • How to refactor this Ruby on Rails code?

    - by yuval
    I want to fetch posts based on their status, so I have this code inside my PostsController index action. It seems to be cluttering the index action, though, and I'm not sure it belongs here. How could I make it more concise and where would I move it in my application so it doesn't clutter up my index action (if that is the correct thing to do)? if params[:status].empty? status = 'active' else status = ['active', 'deleted', 'commented'].include?(params[:status]) ? params[:status] : 'active' end case status when 'active' #active posts are not marked as deleted and have no comments is_deleted = false comments_count_sign = "=" when 'deleted' #deleted posts are marked as deleted and have no comments is_deleted = true comments_count_sign = "=" when 'commented' #commented posts are not marked as deleted and do have comments is_deleted = false comments_count_sign = ">" end @posts = Post.find(:all, :conditions => ["is_deleted = ? and comments_count_sign #{comments_count_sign} 0", is_deleted])

    Read the article

  • ViewPager resize height to Content

    - by user1324936
    ViewPager does not wrap its height to its content. For my layout I need to set the hight then dynamically because it is nested in other layouts. Therefore I created a ScrollView as content of the ViewPager and check its height in onCreate method of the Fragment, but the ScrollView has always the same size. How can I resize the ViewPager to fit to its content? final ScrollView sv = (ScrollView) v.findViewById(R.id.sv); ViewTreeObserver vto = scrollViewMenuFragen.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int height = sv.getMeasuredHeight(); //always same height independent of content height //need to resize ViewPager ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) mPager.getLayoutParams(); params.height = height; mPager.setLayoutParams(params); } });

    Read the article

  • Javascript 'class' and singleton problems

    - by Kucebe
    I have a singleton object that use another object (not singleton), to require some info to server: var singleton = (function(){ /*_private properties*/ var myRequestManager = new RequestManager(params, //callbacks function(){ previewRender(response); }, function(){ previewError(); } ); /*_public methods*/ return{ /*make a request*/ previewRequest: function(request){ myRequestManager.require(request); //err:myRequestManager.require is not a func }, previewRender: function(response){ //do something }, previewError: function(){ //manage error } }; }()); This is the 'class' that make the request to the server function RequestManager(params, success, error){ //create an ajax manager this.param = params; this._success = success; //callbacks this._error = error; } RequestManager.prototype = { require: function(text){ //make an ajax request }, otherFunc: function(){ //do other things } } The problem is that i can't call myRequestManager.require from inside singleton object. Firebug consolle says: "myRequestManager.require is not a function", but i don't understand where the problem is. Is there a better solution for implement this situation?

    Read the article

  • How do you overide a class that is called by another class with parent::method

    - by dan.codes
    I am trying to extend Mage_Catalog_Block_Product_View I have it setup in my local directory as its own module and everything works fine, I wasn't getting the results that I wanted. I then saw that another class extended that class as well. The method I am trying to override is the protected function _prepareLayout() This is the function class Mage_Review_Block_Product_View extends Mage_Catalog_Block_Product_View protected function _prepareLayout() { $this-&gt;getLayout()-&gt;createBlock('catalog/breadcrumbs'); $headBlock = $this-&gt;getLayout()-&gt;getBlock('head'); if ($headBlock) { $title = $this-&gt;getProduct()-&gt;getMetaTitle(); if ($title) { $headBlock-&gt;setTitle($title); } $keyword = $this-&gt;getProduct()-&gt;getMetaKeyword(); $currentCategory = Mage::registry('current_category'); if ($keyword) { $headBlock-&gt;setKeywords($keyword); } elseif($currentCategory) { $headBlock-&gt;setKeywords($this-&gt;getProduct()-&gt;getName()); } $description = $this-&gt;getProduct()-&gt;getMetaDescription(); if ($description) { $headBlock-&gt;setDescription( ($description) ); } else { $headBlock-&gt;setDescription( $this-&gt;getProduct()-&gt;getDescription() ); } } return parent::_prepareLayout(); } I am trying to modify it just a bit with the following, keep in mind I know there is a title prefix and suffix but I needed it only for the product page and also I needed to add text to the description. class MyCompany_Catalog_Block_Product_View extends Mage_Catalog_Block_Product_View protected function _prepareLayout() { $storeId = Mage::app()-&gt;getStore()-&gt;getId(); $this-&gt;getLayout()-&gt;createBlock('catalog/breadcrumbs'); $headBlock = $this-&gt;getLayout()-&gt;getBlock('head'); if ($headBlock) { $title = $this-&gt;getProduct()-&gt;getMetaTitle(); if ($title) { if($storeId == 2){ $title = "Pool Supplies Fast - " .$title; $headBlock-&gt;setTitle($title); } $headBlock-&gt;setTitle($title); }else{ $path = Mage::helper('catalog')-&gt;getBreadcrumbPath(); foreach ($path as $name =&gt; $breadcrumb) { $title[] = $breadcrumb['label']; } $newTitle = "Pool Supplies Fast - " . join($this-&gt;getTitleSeparator(), array_reverse($title)); $headBlock-&gt;setTitle($newTitle); } $keyword = $this-&gt;getProduct()-&gt;getMetaKeyword(); $currentCategory = Mage::registry('current_category'); if ($keyword) { $headBlock-&gt;setKeywords($keyword); } elseif($currentCategory) { $headBlock-&gt;setKeywords($this-&gt;getProduct()-&gt;getName()); } $description = $this-&gt;getProduct()-&gt;getMetaDescription(); if ($description) { if($storeId == 2){ $description = "Pool Supplies Fast - ". $this-&gt;getProduct()-&gt;getName() . " - " . $description; $headBlock-&gt;setDescription( ($description) ); }else{ $headBlock-&gt;setDescription( ($description) ); } } else { if($storeId == 2){ $description = "Pool Supplies Fast: ". $this-&gt;getProduct()-&gt;getName() . " - " . $this-&gt;getProduct()-&gt;getDescription(); $headBlock-&gt;setDescription( ($description) ); }else{ $headBlock-&gt;setDescription( $this-&gt;getProduct()-&gt;getDescription() ); } } } return Mage_Catalog_Block_Product_Abstract::_prepareLayout(); } This executs fine but then I notice that the following class Mage_Review_Block_Product_View_List extends which extends Mage_Review_Block_Product_View and that extends Mage_Catalog_Block_Product_View as well. Inside this class they call the _prepareLayout as well and call the parent with parent::_prepareLayout() class Mage_Review_Block_Product_View_List extends Mage_Review_Block_Product_View protected function _prepareLayout() { parent::_prepareLayout(); if ($toolbar = $this-&gt;getLayout()-&gt;getBlock('product_review_list.toolbar')) { $toolbar-&gt;setCollection($this-&gt;getReviewsCollection()); $this-&gt;setChild('toolbar', $toolbar); } return $this; } So obviously this just calls the same class I am extending and runs the function I am overiding but it doesn't get to my class because it is not in my class hierarchy and since it gets called after my class all the stuff in the parent class override what I have set. I'm not sure about the best way to extend this type of class and method, there has to be a good way to do this, I keep finding I am running into issues when trying to overide these prepare methods that are derived from the abstract classes, there seems to be so many classes overriding them and calling parent::method. What is the best way to override these functions?

    Read the article

  • 1-st level routes for multiple resources in Rails

    - by Leonid Shevtsov
    I have a simple SEO task. There's a City model and a Brand model, and I have to create 1st-level URLs for both (e.g. site.com/honda and site.com/boston). What's the preferred routing/controller combination to do this in Rails? I can only think of map.connect '/:id', :controller => 'catchall', :action => 'index' class CatchallController < ApplicationController def index if City.exists?(:slug => params[:id]) @city = City.find_by_slug!(params[:id]) render 'cities/show' else @brand = Brand.find_by_slug!(params[:id]) render 'brands/show' end end end but it seems to be very un-Rails to put such logic into the controller. (Obviously I need to make sure that the slugs don't overlap in the models, that's done).

    Read the article

  • Getting list of fields back from 'use fields' pragma?

    - by makenai
    So I'm familiar with the use fields pragma in Perl that can be used to restrict the fields that are stored in a class: package Fruit; use fields qw( color shape taste ); sub new { my ( $class, $params ) = @_; my $self = fields::new( $class ) unless ref $class; foreach my $name ( keys %$params ) { $self->{ $name } = $params->{ $name }; } return $self; } My question is.. once I've declared the fields at the top, how I can get the list back.. say because I want to generate accessors dynamically? Is keys %FIELDS the only way? Secondarily, is there a more efficient way to pre-populate the fields in the constructor than looping through and assigning each parameter as I am above? Thanks!

    Read the article

  • Escaping and unescaping a string with single and double quotes in Javascript

    - by Reina
    I have a search box that a user can search for any string including single AND double quotes, once they have searched, the backend is passing the keyword back to me so I can put it back in the box. I don't know what the string is so I can't escape quotes myself, below is an example: var keyword = "hello"; $("#selectionkeywords").val(); The issue I am having is that if the user enters "hello" the keyword becomes ""hello"" and I get this error: missing ) after argument list [Break On This Error] jQuery("#selectionkeywords").val(""hello""); The user could also enter single quotes so that rules it out as well. I tried using escape unescape but I still have the same issue e.g. escape(""hello"") I could get the value in an unescaped format e.g. "hello" but I don't know what to do with it, escape doesn't work on it I end up with this %26%23034%3Bhello%26%23034%3B So I'm pretty much stuck at the moment as I can't do anything to the string, any ideas?

    Read the article

  • PHP OOP: method?

    - by Isis
    Hello <?php class Templater { static $params = array(); public static function assign($name, $value) { self::$params[] = array($name => $value); } public static function draw() { self::$params; } } $test = Templater::assign('key', 'value'); $test = Templater::draw(); print_r($test); How to alter this script so I could use this:? $test = Templater::assign('key', 'value')->assign('key2', 'value2')-draw(); print_r($test);

    Read the article

  • How do I keep a count of undefined strings within a loop using PHP?

    - by mike
    I'm using a loop within a loop to try to generate keyword combinations and also find the ones that have been used the most. My outside loop just queries a list of keywords (lets use "chicago" as our first keyword, 3 records were found). The inside loop finds all the records in the "posts" table where keyword = "chicago". Within this loop, I need to generate strings based on info I found in the database. Which, would look something like "chicago bulls", "chicago bears", "chicago cubs" etc... I know how to do everything up until this point, but how do I temporary hold these generated strings and count how many times they have been found within the 3 records?

    Read the article

  • Cannot get principal id on my Spock test

    - by Ant's
    I have a controller like this : @Secured(['ROLE_USER','IS_AUTHENTICATED_FULLY']) def userprofile(){ def user = User.get(springSecurityService.principal.id) params.id = user.id redirect (action : "show", params:params) } I want to test the controller above controller in spock, so I wrote a test code like this: def 'userProfile test'() { setup: mockDomain(User,[new User(username:"amtoasd",password:"blahblah")]) when: controller.userprofile() then: response.redirectUrl == "/user/show/1" } When I run my test, this test fails with this error message : java.lang.NullPointerException: Cannot get property 'principal' on null object at mnm.schedule.UserController.userprofile(UserController.groovy:33) And in case of Integration test: class UserSpec extends IntegrationSpec { def springSecurityService def 'userProfile test'() { setup: def userInstance = new User(username:"antoaravinth",password:"secrets").save() def userInstance2 = new User(username:"antoaravinthas",password:"secrets").save() def usercontroller = new UserController() usercontroller.springSecurityService = springSecurityService when: usercontroller.userprofile() then: response.redirectUrl == "/user/sho" } } I get the same error as well. What went wrong? Thanks in advance.

    Read the article

  • Failing rspec Rails Tutorial Chapter 9.3

    - by greyghost24
    I am failing 3 tests and I have found numerous examples on here and on on the internet in general but I can't seem to find where I'm going wrong. Thanks for any help. 1) User pages signup with valid information edit page Failure/Error: before { visit edit_user_path(user) } ActionView::Template::Error: undefined method `model_name' for NilClass:Class # ./app/views/users/edit.html.erb:6:in `_app_views_users_edit_html_erb___4113112884365867193_70232486166220' # ./spec/requests/user_pages_spec.rb:96:in `block (5 levels) in <top (required)>' 2) User pages signup with valid information edit page Failure/Error: before { visit edit_user_path(user) } ActionView::Template::Error: undefined method `model_name' for NilClass:Class # ./app/views/users/edit.html.erb:6:in `_app_views_users_edit_html_erb___4113112884365867193_70232486166220' # ./spec/requests/user_pages_spec.rb:96:in `block (5 levels) in <top (required)>' 3) User pages signup with valid information edit page Failure/Error: before { visit edit_user_path(user) } ActionView::Template::Error: undefined method `model_name' for NilClass:Class # ./app/views/users/edit.html.erb:6:in `_app_views_users_edit_html_erb___4113112884365867193_70232486166220' # ./spec/requests/user_pages_spec.rb:96:in `block (5 levels) in <top (required)>' Finished in 0.26515 seconds 3 examples, 3 failures Failed examples: rspec ./spec/requests/user_pages_spec.rb:100 # User pages signup with valid information edit page rspec ./spec/requests/user_pages_spec.rb:99 # User pages signup with valid information edit page rspec ./spec/requests/user_pages_spec.rb:101 # User pages signup with valid information edit page authentication_pages_spec.rb require 'spec_helper' describe "Authentication" do subject { page } describe "signin page" do before { visit signin_path } it { should have_selector('h1', text: 'Sign in') } it { should have_selector('title', text: 'Sign in') } end describe "signin" do before { visit signin_path } describe "with invalid information" do before { click_button "Sign in" } it { should have_selector('title', text: 'Sign in') } it { should have_selector('div.alert.alert-error', text: 'Invalid') } describe "after visiting another page" do before { click_link "Home" } it { should_not have_selector('div.alert.alert-error') } end end describe "with valid information" do let(:user) { FactoryGirl.create(:user) } before do fill_in "Email", with: user.email fill_in "Password", with: user.password click_button "Sign in" end it { should have_selector('title', text: user.name) } it { should have_link('Profile', href: user_path(user)) } it { should have_link('Sign out', href: signout_path) } it { should_not have_link('Sign in', href: signin_path) } describe "followed by signout" do before { click_link "Sign out" } it { should have_link('Sign in') } end end end end Here is the users_controller: class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save sign_in @user flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end end def edit @user = User.find(params[:id]) end edit.html.erb: <% provide(:title, "Edit user") %> <h1>Update your profile</h1> <div class="row"> <div class="span6 offset3"> <%= form_for(@user) do |f| %> <%= render 'shared/error_messages' %> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %> <%= f.label :password %> <%= f.password_field :password %> <%= f.label :password_confirmation, "Confirm Password" %> <%= f.password_field :password_confirmation %> <%= f.submit "Save changes", class: "btn btn-large btn-primary" %> <% end %> <%= gravatar_for @user %> <a href="http://gravatar.com/emails">change</a> </div> here is the user_pages_spec: require 'spec_helper' describe "User pages" do subject { page } describe "profile page" do let(:user) { FactoryGirl.create(:user) } before { visit user_path(user) } it { should have_selector('h1', text: user.name) } it { should have_selector('title', text: user.name) } end describe "signup page" do before { visit signup_path } it { should have_selector('h1', text: 'Sign up') } it { should have_selector('title', text: full_title('Sign up')) } end describe "signup" do before { visit signup_path } describe "with invalid information" do it "should not create a user" do expect { click_button "Create my account" }.not_to change(User, :count) end describe "error messages" do before { click_button "Create my account" } it { should have_selector('title', text: 'Sign up') } it { should have_content('error') } end end describe "with valid information" do before do fill_in "Name", with: "Example User" fill_in "Email", with: "[email protected]" fill_in "Password", with: "foobar" fill_in "Confirmation", with: "foobar" end it "should create a user" do expect do click_button "Create my account" end.to change(User, :count).by(1) end describe "after saving the user" do before { click_button "Create my account" } let(:user) { User.find_by_email('[email protected]') } it { should have_selector('title', text: user.name) } it { should have_selector('div.alert.alert-success', text: 'Welcome') } it { should have_link('Sign out') } end end end describe "signup page" do before { visit signup_path } it { should have_selector('h1', text: 'Sign up') } it { should have_selector('title', text: full_title('Sign up')) } end describe "signup" do before { visit signup_path } let(:submit) { "Create my account" } describe "with invalid information" do it "should not create a user" do expect { click_button submit }.not_to change(User, :count) end end describe "with valid information" do before do fill_in "Name", with: "Example User" fill_in "Email", with: "[email protected]" fill_in "Password", with: "foobar" fill_in "Confirmation", with: "foobar" end it "should create a user" do expect { click_button submit }.to change(User, :count).by(1) end describe "edit" do let(:user) { FactoryGirl.create(:user) } before { visit edit_user_path(user) } describe "page" do it { should have_selector('h1', text: "Update your profile") } it { should have_selector('title', text: "Edit user") } it { should have_link('change', href: 'http://gravatar.com/emails') } end describe "with invalid information" do before { click_button "Save changes" } it { should have_content('error') } end end end end end edit: users_controllers.rb was formatted incorrectly. It should look like this: class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save sign_in @user flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end def edit @user = User.find(params[:id]) end end

    Read the article

  • DataMapper save fails but with no errors

    - by Justin Bozonier
    When I try to modify and then save a model using DataMapper I get a SaveFailure exception but no errors. Specifically I see this message: "MonthlyBill#save returned false, MonthlyBill was not saved" This is the code doing the saving: post '/monthly_bills' do with_authenticated_user do |user| description = params[:description] expected_amount = params[:expected_amount] pay_period = params[:pay_period] monthly_bill = MonthlyBill.new(:description=>description, :expected_amount=>expected_amount, :pay_period=>pay_period) user.MonthlyBills << monthly_bill user.save end The User model: class User include DataMapper::Resource property :id, Serial property :email_address, String property :password, String has n, :MonthlyBills has 1, :CurrentPayPeriod end The MonthlyBill model: class MonthlyBill include DataMapper::Resource property :id, Serial property :description, String property :expected_amount,Decimal property :pay_period, Integer belongs_to :user end What is the issue and, more importantly, how can I get DataMapper to tell me more specifically what is wrong?

    Read the article

< Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >