associations - Rails nested models and virtual attribute initialization -


i have problem understanding how attributes "sent" nested model(s), , if possible model virtual attrubute too. have 3 models:

class user < activerecord::base    ...    has_and_belongs_to_many :clearancegoods    has_many :clearanceitems, through: :user_clearanceitems_descriptions    has_many :user_clearanceitems_descriptions    ... end  class clearanceitem < activerecord::base     ...     has_many :users, through: :user_clearanceitems_descriptions     has_many :user_clearanceitems_descriptions     accepts_nested_attributes_for :user_clearanceitems_descriptions     ...     def user_id         @user_id     end     def user_id=(val)         @user_id = val     end end  class userclearanceitemsdescription < activerecord::base     belongs_to :user     belongs_to :clearanceitem end 

in console:

desc = user.find(5).user_clearanceitems_descriptions.new desc.user_id  ### result 5  item = user.find(5).clearanceitems.new item.user_id ### result in nil 

if clearanceitem can have many users, can't have single user_id, otherwise attribute have have multiple values. if you're trying create clearanceitems associated user, activerecord automagically create associated join record:

user.find(5).clearanceitems.create user.find(5).clearanceitems # contains clearanceitem created 

so remove user_id attribute clearanceitem.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -