【问题标题】:using an array with fields_for使用带有 fields_for 的数组
【发布时间】:2012-06-26 17:17:05
【问题描述】:

如何使用 fields_for 遍历对象数组(所有相同的模型)? 该数组包含由 current_user 创建的对象。

我目前有:

<%= f.fields_for :descriptionsbyuser do |description_form| %>
<p class="fields">
    <%= description_form.text_area :entry, :rows => 3 %>
    <%= description_form.link_to_remove "Remove this description" %>
    <%= description_form.hidden_field :user_id, :value => current_user.id %>
</p>
<% end %>

但我想用我在控制器中创建的数组替换 :descriptionsbyuser - @descriptionsFromCurrentUser

这也在 Ryan Bate 的“nested_form_for”中

任何指针将不胜感激!

亚当

【问题讨论】:

    标签: ruby-on-rails arrays fields-for


    【解决方案1】:

    要使用fields_for 的集合并使其按您期望的方式工作,模型需要接受集合的嵌套属性。如果集合是ActiveRecord 一对多关系,请使用accepts_nested_attributes_for 类宏。如果集合不是 ActiveRecord 一对多关系,则需要实现集合 getter 和集合属性 setter。

    如果是ActiveRecord关系:

    class Person
      has_many :projects
    
      # this creates the projects_attributes= method
      accepts_nested_attributes_for :projects
    end
    

    如果是非ActiveRecord关系:

    class Person
      def projects
        ...
      end
    
      def projects_attributes=(attributes)
        ...
      end
    end
    

    不管怎样,形式都是一样的:

    <%= form_for @person do |f| %>
      ...
      <%= f.fields_for :projects, @active_projects do |f| %>
        Name: <%= f.text_field :name %>
      <% end %>
      ...
    <% end %>
    

    【讨论】:

    • +1 获取非 ActiveRecord 实现细节。不知何故,我的眼睛拒绝看到文档中明确解释的内容......
    【解决方案2】:

    Docs for fields_for向你清晰展示了数组的使用方式:

    或者要使用的集合:

    <%= form_for @person do |person_form| %>
      ...
      <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
        Name: <%= project_fields.text_field :name %>
      <% end %>
      ...
    <% end %>
    

    @active_projects 这是你的数组。

    【讨论】:

    • 这对我不起作用。我收到了类似undefined method 'name' for #&lt;Array:0xaedada0&gt; 的信息。
    • @Ajedi32 et al => 你的模型需要为集合属性实现一个设置器。请参阅鲜为人知的答案。
    【解决方案3】:

    我发现这是最干净的方式

    如果您正在处理直接数据并希望在不使用任何这些@objects 的情况下发回数组

    <%= form_for :team do |t| %>
      <%= t.fields_for 'people[]', [] do |p| %>
        First Name: <%= p.text_field :first_name %>
        Last Name: <%= p.text_field :last_name %>
      <% end %>
    <% end %>
    

    你的参数数据应该像这样返回

    "team" => {
      "people" => [
        {"first_name" => "Michael", "last_name" => "Jordan"},
        {"first_name" => "Steve", "last_name" => "Jobs"},
        {"first_name" => "Barack", "last_name" => "Obama"}
      ]
    }
    

    【讨论】:

      【解决方案4】:

      几乎不知道的答案的补充(由于声誉点无法添加为评论)-

      对于非活动记录的情况,除了*_attributes=(attributes)之外,我还必须在我的班级中定义persisted?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-27
        • 1970-01-01
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多