我有一个带有大量字段(112)的导轨模型,用于加载配置。我希望在编辑和展示形式中只显示,如果该字段已填充。也就是说,如果数据库中的字段为null,则不要显示它以进行编辑。Rails:使用simple_form遍历属性
有两个记录 - 主要是批次,并且与Primer3Batch类有1:1的关系。我试图在批量显示操作上对Primer3Batch类进行编辑,我不确定这是一个好主意还是甚至可以工作。
我已经使用属性方法试图和正在此错误:
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
批次/ 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您指出使用实例变量的错误。我已经纠正它,似乎进一步,但它仍然不完全正确。这是行更改 - 注意属性。每个为属性。每个属性不起作用。
<% @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也是我得到了同样的错误。 – ardochhigh