实例化模型时的质量分配问题
我有一个用户模型(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 未填充。我收到关于在配置文件上设置 :user_id 的批量分配警告,因为我有 attr_accessible 暴露了配置文件上的一些字段。
我不想删除 attr_accessible 但不明白为什么设置一个字段被视为批量分配。我认为这可能与传递哈希有关,因此我尝试了以下解决方法:
@profile = Profile.create
@profile.user_id = self.id
这会删除警告,但用户 ID 仍未在配置文件上设置。解决这个问题的正确方法是什么?
非常感谢任何清晰度! :)
I have a User model (Devise) and have created a Profile model with has_one / belongs_to relationship. I'm trying to automatically create a profile when the User is created as follows :
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
The profile gets created but the user id does not get populated. I get a Mass Assignment warning with regard to setting :user_id on the profile because I have attr_accessible exposing a few fields on the Profile.
I dont want to remove the attr_accessible but dont understand why setting one field is considered mass assignment. I figured this might be to do with passing a hash so Ive tried the following as a workaround :
@profile = Profile.create
@profile.user_id = self.id
This removes the warning but the user_id is still not getting set on the profile. What is the correct way to go about solving this ?
Any clarity much appreciated ! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在解决方法结束时调用@profile.save?
也许你可以尝试这个:
Are you calling @profile.save at the end of your workaround?
Maybe you can try this: