尝试做一个计费应用程序,我有 4 个模型客户,特别是 bill 和 billpart 客户是注册用户,可以有很多账单,账单只能有很多现有细节,我的模型如下
class Customer < ActiveRecord::Base
attr_accessible :name, :ph_no
validates :name, :ph_no, :presence => true
has_many :bills
end
class Particular < ActiveRecord::Base
attr_accessible :part_name, :part_qty
validates :part_name, :presence => true
has_many :billparts
has_many :bills, :through => :billparts
end
class Bill < ActiveRecord::Base
attr_accessible :billdisc, :customer_id
validates :billdisc, :customer_id, :presence => true
belongs_to :customer
has_many :billparts
has_many :particulars, :through => :billparts
end
class Billpart < ActiveRecord::Base
attr_accessible :bill_id, :part_amt, :particular_id
belongs_to :bill
belongs_to :particular
end
我的计费控制器
def new
@bill = Bill.new(customer_id: params[:customer_id])
#billpart
@all_billparts = Billpart.all
@billpart = Billpart.new
@all_particulars = Particular.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @bill }
end
end
我的新计费视图
<%= form_for(@bill) do |f| %>
<% if @bill.errors.any? %>
<div id="error_explanation">
<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">
<%= f.label :customer_id %><br />
<%= f.number_field :customer_id %>
</div>
<%= form_for(@billpart) do |f| %>
<% if @billpart.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@billpart.errors.count, "error") %> prohibited this billpart
from being saved:</h2>
<ul>
<% @billpart.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :bill_id %><br />
<%= f.number_field :bill_id %>
</div>
<div class="field">
<%= f.label :particular_id %><br />
<%= f.collection_select :particular_id, @all_particulars, :id, :part_name %>
</div>
<div class="field">
<%= f.label :part_amt %><br />
<%= f.number_field :part_amt %>
</div>
<div class="actions">
<%= f.submit "Add more" %>
</div>
<% end %>
<div class="field">
<%= f.label :billdisc %><br />
<%= f.number_field :billdisc %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
使用上面的代码尝试生成新账单时不会有任何 bill_id 以及 billpart 将如何获得要关联的 bill_id