我有一个父表单(潜在客户)和子表单(QuoteMetal)(在同一个提交上多次呈现)。表单中的所有信息都会写入各自的数据表,但我需要子表单中的信息来执行查询并返回这些值。我有创建的表单和一个将信息写入数据表的控制器。
我需要帮助为每个子表单创建查询结果,然后在视图中访问它们。这是我现在拥有的。
class LeadsController < ApplicationController
def index
@lead = Lead.new
@quote_metal = @lead.quote_metals.build
end
def create
#raise params.inspect
@lead = Lead.create!(lead_params) #write to data tables (which works)
@lead.quote_metals.each do |f|
@metal = Metal.calculate_metal(f).first #here is where my problem is! the #calculate_metal is the query located in my model
end
end
def show
end
private
def lead_params
params.require(:lead).permit([:name, .....
quote_metals_attributes: [:id...],
quote_melees_attributes: [:shape...],
quote_diamonds_attributes: [:shape...]
])
end
end
和视图:
<div class='container'>
<div class="row">
<div class='col-sm-3 col-sm-offset-2'>
<h3 class="text-center">Your Search: </h3>
</div>
<div class='col-sm-5'>
<h4 class="text-center">Returning estimates for a <%= @metal.metal %> setting
weighing <%= @metal.weight %> <%= @metal.unit %>. I am paying
<%= number_to_currency(@metal.price, precision: 2) %> per <%= @metal.unit %>.</h4>
</div>
</div>
答案 0 :(得分:0)
Actions on QuoteMetal
instances should be handled in the QuoteMetal
class. So, I would replace:
@lead.quote_metals.each do |f|
@metal = Metal.calculate_metal(f).first #here is where my problem is! the #calculate_metal is the query located in my model
end
with:
@lead.quote_metals.each do |f|
f.create
end
And then in your QuoteMetal
class, you can use a before_save callback and perform the calculation there. Keep in mind this will invoke calculate_metal
every time a QuoteMetal
is saved or updated.
Even better would be to use accepts_nested_attributes_for
in the Lead
model so that quote_metals can be automatically created when leads are created. See Rails documentation here. With this approach, you could eliminate the above three lines in the controller, but would still need the callback in the QuoteMetal
class to perform the custom calculation.
Separately, be aware that your call to create!
will raise an exception if validation fails. Not sure you intend that.