0

我有两个模型用户和配置文件。
我想将用户名和密码保存在配置文件中的用户和其他用户配置文件详细信息中。
现在,
用户模型具有:在Rails3中嵌套模型

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 [:用户] )中创建动作

那么,出了什么问题?我也试过把profile_attributes放在attr_accessible中,但它没有帮助!
请帮我找出解决方案。

+1

尝试删除'@profile = @ user.create_profile(params [:profile])'行。你不需要它。 – 2012-08-13 06:28:25

+0

它看起来像你想要传递给@profile的配置文件实际上是用户参数,因此你的用户表单有问题 – megas 2012-08-13 06:35:13

+0

这告诉我你的视图有问题。你的params散列应该有一个':profile_attributes'而不是':profile'键。批量分配失败,因为您没有'profile'属性并且无法访问。如果您在视图中调用fields_for,请确保将它传递给配置文件的模型。可能是'@profile'或'@user.profile',而不是简单的字符串或符号。 – Joeyjoejoejr 2012-08-13 07:24:36

回答

1

首先,按照@nash的建议,您应该从create操作中删除@profile = @user.create_profile(params[:profile])accepts_nested_attributes_for会自动为你创建你的个人资料。

检查您的视图是否为嵌套属性正确设置。应该不应该在params[:profile]中看到任何东西。配置文件属性需要通过params[:user][:profile_attributes]才能使嵌套模型正常工作。

总之,你create动作应该是这样的:

def create 
    @user = User.new(params[:user]) 

    if @user.save 
    redirect_to root_url, :notice => "user created successfully!" 
    else 
    render "new" 
    end 
end 

你的表单视图(通常_form.html.erb)应该是这个样子:

<%= form_for @user do |f| %> 

    Email: <%= f.text_field :email %> 
    Password: <%= f.password_field :password %> 

    <%= f.fields_for :profile do |profile_fields| %> 

    Bio: <%= profile_fields.text_field :bio %> 
    Birthday: <%= profile_fields.date_select :birthday %> 
    Color: <%= profile_fields.text_field :color %> 

    <% end %> 

    <%= f.submit "Save" %> 

<% end %> 

欲了解更多信息,see this old but great tutorial by Ryan Daigle

+0

使用:个人资料不显示任何个人资料字段。问题是在创建新用户时,它具有无法批量分配的配置文件属性。 – usercr 2012-08-13 12:10:21

+0

基本上,如果您正确使用'accep_nested_attributes_for',您将永远不会遇到质量分配保护问题。你真的永远不需要在代码中的任何地方使用'params [:profile]'。你的控制器甚至不需要知道UserProfile存在。我建议你阅读由Ryan Daigle链接到的教程。 – jstr 2012-08-13 12:26:09