2015-10-20 87 views
0

我已經嘗試過在搜索結果中找到的解決方案,但驗證仍然不起作用。 這裏的模型設置: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寶石):

<%= 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> 

回答

0

試試這個:

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

試過這個剛纔,但仍然沒有工作:( –

+0

嘗試使用索引[使用唯一索引備份](http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of#269-Back-it-up-with-a-unique-index) – 2015-10-20 07:56:34

+0

謝謝。它的工作,但是,我得到這個錯誤'SQLite3 :: ConstraintException不唯一'。 –

相關問題