2

I am new to ROR and been trying to fumble my way through the tutorial by mike hartl( excellent read for starters i might add ). There is however something i am struggling with, my user model looks like below.

class User < ActiveRecord::Base

    validates :name , :presence => true, :length => {:maximum => 50 }
    validates :email, :presence   => true,
                    :format     => { :with => email_regex },
                    :uniqueness => true
end

I then open the ruby console using rails -c and create a new user

usr = User.new(:name=>"abcd",:email=>"[email protected]")

I then save it by using

usr.save

This created a new record in my database. So far so good.but if i type usr.save again, nothing happens, i look at the database ( sqlite ) and not even the last update date changed.

Another interesting thing i noticed is when i use

User.create(:name=>"abcd",:email=>"[email protected]"),

multiple times, there is a record created every time i run it in the console.

Can some one please explain why my save does not work and also why my uniqueness constraint is being ignored?

Thanks in advance

1 Answer 1

2

ActiveRecord is smart enough to understand that when you type usr.save twice in a row, the 2nd one is redundant.

usr = User.new
usr.save # usr is saved (if it was valid)
usr.save # usr is already saved and unchanged!  do nothing.
usr.name = "bananas"
usr.save # usr name changed, commit the change!

When you say that a user is created in the console each time you run User.create, are you sure they're actually being created? In console you'll see a User returned each time, but the id would be nil if there had been errors in the create attempt. If you run create! instead you'd see an exception if the User had validation errors (like a duplicate email) and did not save.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. The create indeed created multiple records in my table. The change to validate_uniqueness_of function fixed the creation. Should i exit and reopen my rails console every time i make a code change or is it taken care of automatically.
oh yes, that would have done it. You need to reload the console when you make code changes, or at least run load user.rb, for example, to reload the changed class. Although things tend to get a little weird when you do that (for example validations would be included each time and run multiple times afterward).
@user993797 You can just type reload! in rails console and it will reload (almost) everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.