-1

I have a problem understanding how are attributes "sent" to nested model(s), and if is possible to do this for model with virtual attrubute too. I have three 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 is 5

item = User.find(5).clearanceitems.new
item.user_id
### result in nil
Kovo
  • 434
  • 4
  • 14

1 Answers1

0

If Clearanceitem can have many users, then it can't have a single user_id, otherwise that attribute would have to have multiple values. If you're just trying to create Clearanceitems associated with the User, ActiveRecord will automagically create the associated join record:

User.find(5).clearanceitems.create
User.find(5).clearanceitems # Contains the Clearanceitem you just created

So just remove the user_id attribute from Clearanceitem.

depquid
  • 726
  • 7
  • 20