I'm trying to create an application with Ruby on Rails 4.2.1 and PostgreSQL.
I have the following models.
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
and the following actions
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
The output for the params is:
{
"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"
}
}
}
The thing is, I have to add current_builder.id
to every model, Bill
and BillPartial
for instance. What is the best way to add the current_builder.id
to the builder_id
on the BillPartial
model?
Well, after looking for something, I solved this by defining
before_create do
self.builder_id = bill.try(:builder_id)
end
On the BillPartial model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.