【发布时间】:2012-08-13 06:25:44
【问题描述】:
我有两个模型用户和个人资料。
我想将用户名和密码保存在个人资料中,并将其他用户个人资料详细信息保存在个人资料中。
现在,
用户模型有:
has_one :profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password
配置文件模型有
belongs_to :user
attr_accessible :bio, :birthday, :color
用户控制器有
def new
@user = User.new
@profile = @user.build_profile
end
def create
@user = User.new(params[:user])
@profile = @user.create_profile(params[:profile])
if @user.save
redirect_to root_url, :notice => "user created successfully!"
else
render "new"
end
end
new.html.erb 视图包含用户和个人资料的字段。
但是,当我运行此 Web 应用程序时,它显示错误:
无法批量分配受保护的属性:配置文件
在调试它停留在 @user = User.new(params[:user]) 在创建操作
那么,怎么了?我也尝试将 :profile_attributes 放在 attr_accessible 中,但没有帮助!
请帮我找出解决方案。
【问题讨论】:
-
尝试删除
@profile = @user.create_profile(params[:profile])行。你不需要它。 -
看起来您打算传递给@profile 的配置文件参数实际上是要传递给用户参数的,因此您的用户表单中有问题
-
这告诉我你的观点有问题。您的参数哈希应该有一个
:profile_attributes而不是:profile键。批量分配失败,因为您没有profile属性并且无法访问。如果您在视图中调用 fields_for,请确保将模型传递给配置文件。可能是@profile或@user.profile而不仅仅是该名称的字符串或符号。 -
@Joeyjoejoejr ,我在 field_for 中使用了 Atprofile 并且 2all 问题出在 Atuser = User.new(params[:user])
-
是的,正如我所说,你的问题是 field_for 返回的参数应该在键
profile中,它们应该在键profile_attribures中,应该在你的 attr_accessible 调用中.当您尝试保存时,rails 正在寻找不存在的配置文件属性或方法,profile_attributes由accepts_nested_attributes_for添加。还要确保您的 fields_for 调用嵌套在用户模型的 form_for 调用中。
标签: ruby-on-rails ruby-on-rails-3 activerecord actioncontroller