【问题标题】:Rails 4 new record from different model来自不同型号的 Rails 4 新记录
【发布时间】:2014-09-22 02:36:10
【问题描述】:

我目前正在开发基于 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

我想做的是根据 Estimate 记录创建一个新订单。如果我创建一个新订单并显示编辑页面,则一切正常:

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

但我想使用“新建”操作并仅在编辑和确认后创建记录。

我尝试使用

redirect_to new_customer_order_path(old_estimate.customer, old_estimate.attributes)

它将呈现新的表单,但其中没有任何参数。 参数在 URL 中,但我在日志中得到“Unpermitted parameters:”。在 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]

有人有什么建议吗?

【问题讨论】:

  • 你能解决这个@paulwang 吗?我也面临着类似的困境。

标签: ruby-on-rails activeadmin


【解决方案1】:

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

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

相应的输入将被填充。

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多