你應該在這種情況下使用多態關聯。在這裏,你可以做實現這一目標是什麼:
class Bill < ActiveRecord::Base
has_many :items # establish association with items!
# to save items in bill only if they are there!
accepts_nested_attributes_for :items, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
在item.rb的#模型文件:
class Item < ActiveRecord::Base
belongs_to :bill # establish association with bill!
end
在你bills_controller.rb建立正常
在bill.rb#模型文件
動作:index, new, create, show, edit, update, delete
的更新動作:
def update
@bill = Bill.find(params[:id])
respond_to do |format|
if @bill.update_attributes(params[:bill])
format.html { redirect_to(@bill, :notice => 'Bill was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @bill.errors, :status => :unprocessable_entity }
end
end
end
,你做的不是H AVE打擾你items_controller.rb創建任何動作/方法,只是在創建視圖/項目/ _form.html.erb部分_form.html.erb,並把這個:
<%= form.fields_for :items do |item_form| %>
<div class="field">
<%= tag_form.label :name, 'Item:' %>
<%= tag_form.text_field :name %>
</div>
<div class="field">
<%= tag_form.label :quantity, 'Quantity:' %>
<%= tag_form.text_field :quantity %>
</div>
<% unless item_form.object.nil? || item_form.object.new_record? %>
<div class="field">
<%= tag_form.label :_destroy, 'Remove:' %>
<%= tag_form.check_box :_destroy %>
</div>
<% end %>
<% end %>
現在你必須調用這從您的視圖/計費/ _form.html.erb:
<% @bill.tags.build %>
<%= form_for(@bill) do |bill_form| %>
<% if @bill.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@bill.errors.count, "error") %> prohibited this bill from being saved:</h2>
<ul>
<% @bill.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= bill_form.label :name %><br />
<%= bill_form.text_field :name %>
</div>
<h2>Items</h2>
<%= render :partial => 'items/form',
:locals => {:form => bill_form} %>
<div class="actions">
<%= bill_form.submit %>
</div>
<% end %>
查看/票據/ new.html.erb:
<h1>New Bill</h1>
<%= render 'form' %>
<%= link_to 'Back', bills_path %>
查看/票據/ edit.html.erb:
個
<h1>Editing Bill</h1>
<%= render 'form' %>
<%= link_to 'Show', @bill %> |
<%= link_to 'Back', bills_path %>
問候, 蘇里亞
@Surya您好,感謝詳細的回答,會嘗試了這一點 – sameera207 2011-04-19 17:37:03