0

User モデル (Devise) があり、has_one / belongs_to 関係を持つ Profile モデルを作成しました。次のようにユーザーが作成されたときに、プロファイルを自動的に作成しようとしています:

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 を設定すると一括割り当て警告が表示されます。

attr_accessible を削除したくありませんが、1 つのフィールドの設定が一括割り当てと見なされる理由がわかりません。これはハッシュを渡すことに関係している可能性があると考えたので、回避策として次のことを試しました。

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

これにより警告は削除されますが、user_id はまだプロファイルに設定されていません。これを解決する正しい方法は何ですか?

どんな明確さでも大歓迎です!:)

4

1 に答える 1

1

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

多分あなたはこれを試すことができます:

def create_profile
  self.build_profile.save
end
于 2011-07-29T16:51:52.487 に答える