【问题标题】:Rails: Iterate through attributes with simple_formRails:使用 simple_form 遍历属性
【发布时间】:2013-06-23 10:19:46
【问题描述】:

我有一个带有大量字段 (112) 的 rails 模型,用于加载配置。我想在编辑和显示表单中,仅显示如果该字段已填写。也就是说,如果该字段在数据库中为 null,则不要显示它以供编辑。

有两条记录——主要的一条是 Batch,与 Primer3Batch 类有 1:1 的关系。我正在尝试在 Batch 的显示操作中对 Primer3Batch 类进行编辑,我不确定这是一个好主意还是会起作用。

我已尝试使用 attributes 方法并收到此错误:

undefined method `attributes' for #<SimpleForm::FormBuilder

batches_controller.rb

def show
  @batch = Batch.find(params[:id])
  @primer3 = Primer3Batch.where(:batch_id => @batch.id)[0]

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @batch }
  end
end

batches/show.html.erb

<h1>Batch Details: <%= @batch.id %></h1>

<%= simple_form_for(@primer3) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <% f.attributes.each_attribute do |a| %>
      <% if a %><%# if a is not nil %>
        <%= f.input a %><%# send the field to the form %>
      <% end %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %> 

编辑

感谢JSWorld指出使用实例变量的错误。我已经纠正了它,似乎已经走得更远了,但它仍然不太正确。这是更改的行 - 请注意 attributes.each 因为 attributes.each_attribute 不起作用。

<% @primer3.attributes.each do |a| %>

现在我在表单字段上遇到错误:

undefined method `["id", 110]' for #<Primer3Batch:

我想我需要以某种方式改变这个:

a   ["id", 110]

进入:

<%= f.input :id %>

* 编辑 2 *

基于 IIya Khokhryakov 的回答的最终代码块。

<%= simple_form_for(@primer3) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <% @primer3.attributes.each_pair do |name, value| %>
      <%= f.input name if value %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

【问题讨论】:

  • 我已经用 form_for 尝试了上面的方法,我得到了同样的错误。

标签: ruby-on-rails simple-form


【解决方案1】:

我希望你的意图是@primer3.attributes 而不是f.attributes。错误是因为f 是表单对象并且没有与之关联的attributes

【讨论】:

    【解决方案2】:

    @primer3.attributes 是模型属性及其值的哈希。所以你可以这样做:

    <% @primer3.attributes.each_pair do |name, value| %>
      <%= f.input name if value %>
    <% end %>
    

    【讨论】:

    • 太棒了!谢谢IIya,这正是我想要的。这是一个非常有用的模式。我将使用最终代码更新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2014-10-25
    • 1970-01-01
    • 2012-10-29
    • 2016-08-11
    • 2016-05-12
    相关资源
    最近更新 更多