【问题标题】:Nested forms in rails - accessing attribute in has_many relationrails中的嵌套表单-访问has_many关系中的属性
【发布时间】:2010-02-12 01:50:53
【问题描述】:

我有一个用户和一个配置文件模型。一个用户可以有多个配置文件。在用户创建过程中,我只需要从我的用户模型中的个人资料部分(即电话号码)访问一个信息。因此,我试图通过attr_accessible 来完成它。我的 user.rb 看起来像这样。

has_many :profiles
attr_accessible :handle, :email, :password, :profile_mobile_number
attr_accessor : :profile_mobile_number

我面临的问题是,当我尝试在 user.rb 的方法中调用 getter 方法 profile_mobile_number 时(该方法是私有的,尽管我认为没关系),我得到一个 null价值。我在 users/new.html.erb 表单中使用以下内容

我的问题是这样做的正确方法是什么?我应该使用<% f.fields_for :profile do |ff| -%> 还是<% f.fields_for :profiles do |ff| -%>(注意第二个是复数)。当我使用复数 :profiles 时,我什至看不到表单上的字段。我在这里想念什么?模型 user.rb 中需要使用的时态是什么? :profile_phone_number 还是 :profiles_phone_number?谢谢。

【问题讨论】:

  • 就像我说的那样,我正在使用 f.fields_for :profiles 并且表单中的字段没有显示出来。原来我必须在控制器中添加@user.profiles.build。但现在我无法在 user.rb 中同时拥有 attr_accessible 和 accept_nested_attributes_for。前者优先于后者。但是我确实希望对用户模型的属性具有 attr_accesible 属性,同时不限制对配置文件模型属性的访问。有任何想法吗?谢谢。

标签: ruby-on-rails ruby nested-forms


【解决方案1】:

您可以执行以下操作:

<% form_for @user, :url => { :action => "update" } do |user_form| %>
  ...
  <% user_form.fields_for :profiles do |profiles_fields| %>
     Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
   <% end %>
<% end %>

但是既然你已经有了关联,那还不如用'accepts_nested_attributes_for'

【讨论】:

  • 值得一提的是,它迭代了已经存在的关联对象。但是,它不会创建要填充的新空记录。如果关联中没有新记录,则使用帮助器附加新记录,例如“def setup_profiles(user); user.profiles.build if user.profiles.blank? || !user.profiles.map(&:new_record? ).any?; user; end",然后使用 "form_for setup_profiles(@user) do ..."
  • @hurikhan77 的评论至关重要!如果不存在关联对象,则需要构建一个新对象,否则表单中不会显示任何内容!
【解决方案2】:

你应该看RailsCasts Nested Model Form
谢谢Ryan Bates 干得好。

【讨论】:

  • 是的,Ryan 想出了一个很好的解决方案。
【解决方案3】:

http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for

这个 api 停靠链接列出了许多嵌套属性示例,包括一对一、一对多。很有帮助!

【讨论】:

    【解决方案4】:

    您可以使用 'accepts_nested_attributes_for' 来执行此操作;但是表格有一个小技巧:

    您必须使用单数,并为每个配置文件调用 fields_for,如下所示:

    <% form_for @user do |f| -%>
    <% @user.profiles.each do %>
    <% f.fields_for :profile_attributes, profile do |ff| -%>
    <% end %>
    

    注意是 :profile_attributes,而不仅仅是 :profile

    【讨论】:

    • 如果是一个belongs_to polymorphic关联,你必须在你的用户模型中定义一个build_profile方法。
    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2012-11-15
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多