我有一个模态“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>