我有一个模式“ A ”, 它有一个与 has_ many 关联的直线项目模型“ B ” 。 这意味着 B 与 A 关联。 我对 A 模式 B 的验证
validates_presence_f :B
validates_associated :B
now in my form i have used "fields_for" to save values of B, if i submit a blank form than validation fails and displays an error message for presence of line item B, but the fields of B s disabled, i have to reshow their fields. Can any one predict why this is happening.
here is my model : Model 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>