Rails保存文件复选框

时间:2011-08-04 01:05:40

标签: ruby ruby-on-rails-3 forms checkbox nested-attributes

如何选中该复选框,我该怎么做才能存储我的信息。以下是我到目前为止的情况:

<% @extra.each do |extra| %>
  <%= f.fields_for :purchaseds do |builder| %>
    <div class="label-field">
      <%= builder.label :name, extra.name %>
      <p><%= extra.description %></p>
    </div>
    <div class="text-field">
      $<%= extra.price %>
      <%= builder.check_box :purchased %>
    </div>

    #I WOULD LIKE THIS TO ONLY GET SAVED IF THE CHECK BOX FOR PURCHASED IS CHECKED
    <%= builder.hidden_field :name, :value => extra.name %>
    <%= builder.hidden_field :description, :value => extra.description %>
    <%= builder.hidden_field :price, :value => extra.price %>  
  <% end %>
<% end %>

我的客户要求能够自己添加额外的服务,然后用户可以选择是否想要购买它们作为订单的附件。所以我做的是我创建了一个名为Extra(用于额外服务)的表和另一个名为Purchased的表。购买属于Order,是一个嵌套属性。

1 个答案:

答案 0 :(得分:1)

在您购买的模型中添加验证:

  validates_presence_of :name, :description, :price, :if => :purchased

<强>更新

中为您购买的父模型添加:reject_if选项
accepts_nested_attributes_for :purchaseds, :reject_if => {|attrs| !attrs[:purchased]}