我正在尝试使用Ruby on Rails 4.2.1和PostgreSQL创建一个应用程序。
我有以下型号。
class Builder < ActiveModel
has_many :bills
has_many :bills_partials
end
class Bill < ActiveModel
belongs_to :builder
has_many :bills_partials
accepts_nested_attributes_for :bills_partial, :reject_if => :all_blank, :allow_destroy => true
end
class BillPartial < ActiveModel
belongs_to :builder
belongs_to :bills
end
以及以下行动
def new
bill.bills_partials.build
end
def create
@bill = Bill.scoped_to(current_builder).new(bill_partial_params)
if @bill.save
redirect_to bills_path, flash: { success: t('flash.generic.female.created', model: Bill.model_name.human) }
else
render :new
end
end
private
def bill
@bill ||= Bill.scoped_to(current_builder).find_by(id: uuid_or_nil(params[:id])) || Bill.scoped_to(current_builder).new
end
helper_method :bill
def bill_params
params
.require(:bill)
.permit(:description,
:value,
:date,
bills_partials_attributes: [:id,
:due_date,
:valor,
:_destroy])
end
参数的输出是:
{
"description"=>"some desc",
"value"=>"123",
"date"=>"10/10/2010",
"bills_partials_attributes" =>
{
"0" =>
{
"due_date"=>"14/03/2003",
"value"=>"123"
},
"1" =>
{
"due_date"=>"14/03/2003",
"value"=>"123"
}
}
}
问题是,我必须为每个模型添加current_builder.id
,例如Bill
和BillPartial
。将current_builder.id
添加到builder_id
模型上的BillPartial
的最佳方法是什么?
答案 0 :(得分:0)
好吧,在寻找了什么之后,我通过定义
解决了这个问题before_create do
self.builder_id = bill.try(:builder_id)
end
在BillPartial模型上。