Rails 4来自不同型号的新记录

时间:2014-09-20 09:39:43

标签: ruby-on-rails activeadmin

我目前正在开发基于rails的应用程序来管理订单。 (Rails 4.1.5和ActiveAdmin)

我有这些模特:

class Customer < ActiveRecord::Base
  has_many :estimates
  has_many :orders
  accepts_nested_attributes_for :estimates, :allow_destroy => true
  accepts_nested_attributes_for :orders, :allow_destroy => true
end
class Order < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items, as: :cartable
  accepts_nested_attributes_for :line_items, :allow_destroy => true
end
class Estimate < ActiveRecord::Base
  belongs_to :customer
  has_many :line_items, as: :cartable
  accepts_nested_attributes_for :line_items, :allow_destroy => true
end

我想要做的是根据估算记录创建新订单。如果我创建新订单并使用以下内容显示编辑页面,那么事情就会起作用。

member_action :confirm, :method => :get do
  old_estimate = Estimate.find(params[:id])
  new_estimate = Order.create(old_estimate.attributes.merge({:id => nil, :created_at =>
    nil,:updated_at => nil}))   
  old_estimate.line_items.each do |li|
    new_estimate.line_items.create(li.attributes.merge({:id => nil, :created_at => nil,   
      :updated_at => nil}))
    end
  redirect_to edit_customer_order_path(new_estimate.customer, new_estimate)
end

但我想使用&#34; new&#34;只有在编辑和确认后才能创建记录。

我尝试使用

redirect_to new_customer_order_path(old_estimate.customer, old_estimate.attributes)

它将呈现新表单,但不包含任何参数。 params在URL中,但是我得到了一个&#34; Unpermitted参数:&#34;在日志中。所有参数都在Active Admin下允许(在other.rb和estimate.rb下):

  permit_params :id, :customer_id, :title, :edd, :total,
            line_items_attributes: [:id, :cartable_id, :cartable_type, :product_type, :source_lang, :dest_lang, :unit_price, :total, :_destroy]

有人有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以覆盖新操作以在表单中设置一些默认值:

controller do
  def new
    record = YourActiveRecordModel.new #or find, if you pass id
    record.some_attribute = some_value
    new!
  end
end

将填写相应的输入。