Rails ActiveRecord:嵌套模型的唯一性验证

时间:2015-10-20 07:45:39

标签: ruby-on-rails activerecord

我已尝试过在搜索结果中找到的解决方案,但验证仍然无效。 这是模型设置:

class Transaction < ActiveRecord::Base
    has_many :trans_items, class_name: "TransItem", dependent: :destroy, inverse_of: :transact
    accepts_nested_attributes_for :trans_items

class TransItem < ActiveRecord::Base
    belongs_to :transact, class_name: "Transaction", foreign_key: :transaction_id, inverse_of: :trans_items
    validates_uniqueness_of :material_id, :scope => :transaction_id
end

这仍然成功创建:

Transaction
> trans_items
 - material_id: 9
 - transaction_id: 1
> trans_items
 - material_id: 9
 - transaction_id: 1

更新1:

如下所示,我也试过这个解决方案,但仍然没有工作:

validates :material_id, uniqueness: { scope: :transaction_id }

如果有用,创建表单就是这个(使用nested_form gem):

<%= f.link_to_add "Add Material", :trans_items, :data => { :target => "#trans_items" }  %>
  <table id="trans_items" class="table table-condensed" cellspacing="0">
   <%= f.fields_for :trans_items, wrapper: false do |builder| %>
      <tr class="fields">
        <td width="10%">
          <%= builder.label :qty %><br>
          <%= builder.number_field :qty, :class => 'form-control input-sm', :step => 'any' %>
        </td>
        <td>
          <%= builder.label :material_id %>
          <%= builder.collection_select(:material_id, Material.all, :id, :material_display_dropdown, {prompt: "Select one..."}, { :class => "form-control input-sm" })  %>
        </td>
        <td>
          <%= f.link_to_remove "Remove" %>
        </td>
      </tr> 
    <% end %>
  </table>

1 个答案:

答案 0 :(得分:0)

试试这个:

validates :material_id, uniqueness: { scope: :transaction_id }