Tuesday, November 30, 2010

[Rails] please explain me why nil?

I have 3 models
Skill, User, UserSkill

User has_many skills :through => :user_skills
User has_many :user_skills

UserSkill.new # => { :id => nil, :user_id => nil, :skill_id => nil }
us = UserSkill.create(:user_id => 1, :skill_id => 1) # => { :id => nil,
:user_id => 1, :skill_id => 1 }

Why id is nil?
In the database record was created and id is not null...

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

2 comments:

  1. Because the record had not saved. Call create! instead to raise an exception.

    ReplyDelete
  2. but in general you should create the associations through your model objects.
    So for example:

    u = User.new
    u.skills << Skill.find(1)
    u.save!

    ReplyDelete