0

私はUserモデル(Devise)を持ち、has_one/belongs_to関係でプロファイルモデルを作成しました。モデルをインスタンス化する際の質量代入の問題

class User < ActiveRecord::Base 
    has_many :videos, :dependent => :destroy 
    has_one :profile, :dependent => :destroy 

    after_create :create_profile 

    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :confirmable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    protected 

    def create_profile 
    Profile.create :user_id => self.id 
    end 

end 

プロファイルは作成されますが、ユーザーIDは入力されません。プロファイルは自動的に作成されます。 attr_accessibleがプロファイルのいくつかのフィールドを公開しているため、プロファイルのuser_idを設定するためのMass Assignment警告が表示されます。

私はattr_accessibleを削除したくありませんが、なぜ1つのフィールドを設定するのが質量割り当てと見なされるのか理解できません。

@profile = Profile.create 
@profile.user_id = self.id 

これは警告を削除しますが、user_idのは、まだプロファイルに設定され取得されていません。私は、アイブ氏は、回避策として、次の試してみましたので、これはハッシュを渡すと関係するかもしれない考え出しました。これを解決する正しい方法は何ですか?

非常にわかりやすい! :)

答えて

1

回避策の最後に@ profile.saveを呼び出していますか?

たぶん、あなたはこれを試すことができます。

def create_profile 
    self.build_profile.save 
end 
関連する問題