如何在rails3中实现父子关系?



我正在rails3中创建一个账单应用程序,当涉及到创建账单时,我有一个困惑。

一张账单可以有一个或多个项目

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

我的要求如下

我应该能够创建一个新的账单并向其中添加项目(可以添加任何数量的项目)

我的问题是

1 -要获得要保存在bill_details表中的项目,我应该首先生成bill_id,生成这个账单id的最佳方法是什么?

2 -实现这种场景的最佳方法是什么

3 -我可以得到任何帮助从rails嵌套表单

感谢

干杯sameera

您应该在此场景中使用多态关联。下面是实现这一目标的方法:

的法案。rb# model file:

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

项。rb# model file:

class Item < ActiveRecord::Base
      belongs_to :bill  # establish association with bill!
end

在你的bills_controller。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

,你不需要在你的items_controller中创建任何动作/方法。Rb,只创建一个部分_form.html。view/Items/_form.html中的动词。动词,加上这个:

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

现在你必须从你的视图中调用它/bills/_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 %>

问候,叙利娅

最新更新