モーダル「A」があり、それには has_many 関連付けを持つ line_item モデル「B」があります。これは、B が A に関連付けられていることを意味します。私は、A のモデルで B を検証しています。
validates_presence_f :B
validates_associated :B
今私のフォームでは、「fields_for」を使用して B の値を保存しました。空白のフォームを送信すると、検証が失敗し、行項目 B の存在に関するエラー メッセージが表示されますが、B のフィールドが無効になっているため、フィールドを再表示する必要があります。 . なぜこれが起こっているのか誰でも予測できますか?
ここに私のモデルがあります: モデル A:
class Purchase < ActiveRecord::Base
has_many :purchase_line_items
accepts_nested_attributes_for :purchase_line_items, :reject_if => lambda {|a| a[:account_id].blank? }, :allow_destroy =>true
validates_presence_of :purchase_line_items
validates_associated :purchase_line_items
end
およびモデル B:
class PurchaseLineItem < ActiveRecord::Base
belongs_to :purchase
end
私のコントローラーで:
class PurchasesController < ApplicationController
def new
@purchase = Purchase.new
@purchase.purchase_line_items.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @purchase }
end
end
end
そして最後に私の見解:
<%= form_for @purchase, :html => {:multipart => true} do |f| %>
<%= render 'shared/form_error', :object => @purchase %>
<% @purchase.purchase_line_items.each_with_index do |purchase_line_item, index| %>
<%= render "purchase_line_items", :purchase_line_item => purchase_line_item, :index => index %>
<% end %>
<%= f.submit %>
<% end %>
そして、ラインアイテムの部分的に私は持っています:
<tr id="row<%= index %>" valign="top" >
<%= hidden_field_tag "purchase[purchase_line_items_attributes][#{index}][id]",purchase_line_item.id%>
<td valign="top">
<%= select_tag "purchase[purchase_line_items_attributes][#{index}][account_id]", options_from_collection_for_select(@to_accounts, :id, :name,:selected => purchase_line_item.account_id ), :include_blank => true, :class=>"full" %>
</td>
<td><%= text_field_tag "purchase[purchase_line_items_attributes][#{index}][amount]", purchase_line_item.amount, :class => 'full', :id => 'total', :readonly => 'readonly', :size => 5%></td>
<td><%= link_to image_tag("/images/black_icon/ic_cancel.png"),{:action => :remove_line_item, :index => index}, :remote => true unless index == 0 %></td>
</tr>