-1

ネストされたモデルに属性がどのように「送信」されるかを理解するのに問題があります。また、仮想属性を持つモデルでもこれを行うことができるかどうか。私は3つのモデルを持っています:

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

コンソールで:

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
4

1 に答える 1

0

Clearanceitem が多くのユーザーを持つことができる場合、単一user_idの を持つことはできません。それ以外の場合、その属性は複数の値を持つ必要があります。User に関連付けられた Clearanceitems を作成しようとしているだけの場合、ActiveRecord は関連付けられた結合レコードを自動的に作成します。

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

user_idしたがって、から属性を削除するだけClearanceitemです。

于 2016-01-27T17:50:05.060 に答える