【问题标题】:Nested model in Rails3Rails3 中的嵌套模型
【发布时间】: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_attributesaccepts_nested_attributes_for 添加。还要确保您的 fields_for 调用嵌套在用户模型的 form_for 调用中。

标签: ruby-on-rails ruby-on-rails-3 activerecord actioncontroller


【解决方案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

【讨论】:

  • 使用 :profile 不显示任何配置文件字段。问题是在创建新用户时,它具有无法批量分配的配置文件属性。
  • 好吧,如果您正确使用accepts_nested_attributes_for,您将永远不会遇到批量分配保护问题。你真的不需要在代码中的任何地方使用params[:profile]。您的控制器甚至不需要知道 UserProfile 存在。我建议您阅读我链接到的 Ryan Daigle 的教程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 2011-04-08
  • 2017-07-06
  • 2015-06-05
  • 1970-01-01
相关资源
最近更新 更多