Ruby on rails 创建具有现有子级的父级
有人知道如何用现有的子项创建新的父项吗Ruby on rails 创建具有现有子级的父级,ruby-on-rails,nested-attributes,Ruby On Rails,Nested Attributes,有人知道如何用现有的子项创建新的父项吗 class Order < ActiveRecord::Base has_many :jobs accepts_nested_attributes_for :jobs end class Job < ActiveRecord::Base belongs_to :quote belongs_to :order end 在订单控制器中: def new quote_id @quote = Quote.find(quote_i
class Order < ActiveRecord::Base
has_many :jobs
accepts_nested_attributes_for :jobs
end
class Job < ActiveRecord::Base
belongs_to :quote
belongs_to :order
end
在订单控制器中:
def new quote_id
@quote = Quote.find(quote_id)
@order = Order.new
在我看来
<%= simple_form_for @order, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :quote_id, value: @quote.id, as: :hidden %>
<%= f.input :account_number %>
...
<table>
<thead><tr> ... column headings here ... </tr></thead>
<tbody>
<% @quote.jobs.each do |q| %>
<tr>
<td><%= q.description %></td>
<td><%= q.price %></td>
</tr>
<% end %>
<tr><%= ... add a row with the total price ... %></tr>
</tbody>
</table>
<%= f.button :submit, "Place My Order" %>
<% end $>
我更喜欢的是将作业参数作为表单中的嵌套对象处理,以便在使用Order.id和一些其他参数创建订单时自动更新它们。我试过(在控制器中)
@order=order.new
@quote.jobs.each do| job|
@order.jobs由于订单接受作业的嵌套属性,我认为您可以在构建订单表单时手动创建并填充嵌套作业字段(作为隐藏字段)
<% @quote.jobs.each_with_index do |job, index| %>
<input type='hidden' name='order[jobs_attributes][<% index %>][FIELDNAME]' id='order_jobs_attributes_<% index %>_FIELDNAME' value='<% job.something %>' />
<% end %>
我相信有一种更简洁的方法可以让简单的表单/表单助手使用=f.input
来构建隐藏字段,但我承认我在上面很懒 在您的UI或相关代码中,您如何加载将与此新订单对象关联的现有作业对象/您如何向应用程序提交数据(通过web UI中的表单的post/create调用等)?对我来说,不知道您的代码如何接收要关联的数据会使提供潜在解决方案变得更加困难。您可以发布视图代码以查看您在其中实际执行的操作吗?事实上,我错了。使用我上面帖子的最后一部分,@order.jobs
def create
...
if @order.save
Quote.find(params[quote_id]).jobs.each do |job|
job.update(order_id: @order.id)
end
end
...
@order = Order.new
@quote.jobs.each do |job|
@order.jobs << job
end
<% @quote.jobs.each_with_index do |job, index| %>
<input type='hidden' name='order[jobs_attributes][<% index %>][FIELDNAME]' id='order_jobs_attributes_<% index %>_FIELDNAME' value='<% job.something %>' />
<% end %>