2011-04-18 27 views
0

我在rails3中創建了一個計費應用程序,在創建賬單時我感到困惑。我如何在rails3中實現親子關係

一個法案能有一個或多個項目

'bill' has many 'items' 
'item' belongs to 'bill' 

我的要求如下

我應該能夠創建一個新的法案,並添加項目(可以添加任何數量的項目)

我的問題是

1 - 獲得物品被保存在bill_details表我應該先產生bill_id,什麼是產生最好的辦法賬單ID。

2 - 什麼是執行這樣的

3方案的最佳方式 - 我可以得到任何幫助,從軌道嵌套形式

感謝

歡呼 sameera

回答

0

你應該在這種情況下使用多態關聯。在這裏,你可以做實現這一目標是什麼:

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

問候, 蘇里亞

+0

@Surya您好,感謝詳細的回答,會嘗試了這一點 – sameera207 2011-04-19 17:37:03