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...

ps. rails 3.0.3

The id is not allocated until the record is saved to the database.

Colin

Colin Law wrote in post #965064:

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...

Hi,

Friend when you create any "new" object usign UserSkill or any class class which is associated with ActiveRecords.. then it auto create one hash with all attributes of user_skills(or any relevant) table.. this is due to ORM feature of the Rails..

Second thing, that all values seems to nil in that hash.. this is because it provide you blank hash.. to do process or to assign required values to the attributes..

nil is just because as we know ruby has greate feature of NilClass to avoid exceptions on nil values..

I dont know is this answer of your question or not.

Good luck :wink:

-Ganesh K.

But other models returns the id on ".create()"

yes..

in this case method(".create()") first creates record in db table and then it provides you hash with table's all attributes and values which are there in db records.

-Ganesh K

Model.create(:attr => "value") returns the "#<Model id: 1, attr: Value>" if model is valid and no database's errors found. It is normal, but my UserSkill returns "#<UserSkill id: nil, etc.. >" on create method.