RoR:在表单中嵌套对象的before_save?

时间:2009-11-14 04:28:15

标签: ruby-on-rails forms nested

我有一个带有嵌套对象(客户< order)的表单,除了它不断创建新的客户记录外,它的工作原理。

我想检查现有客户是否已经存在于数据库中(使用客户的电子邮件地址进行搜索),如果是,只需将订单附加到现有记录,但如果没有,继续创建新的客户记录。

我必须在before_save模型中使用order调用,但我不知道如何传递表单参数(电子邮件地址) ) 在那里。这是正确的方法,还是有其他方法?


应用/模型/ order.rb:

class Order < ActiveRecord::Base
  belongs_to :customer
  ...
  accepts_nested_attributes_for :customer
  ...
end

应用/模型/ customer.rb:

class Customer < ActiveRecord::Base
  has_many :orders
  ...
end

应用/控制器/ orders_controller.rb:

def new
  @order = Order.new
  @order_number = "SL-#{Time.now.to_i}"
  @order.customer = Customer.new
  @services_available = Service.all
end

def create
  @order = Order.new params[:order]

  if @order.save
    flash[:notice] = 'Order was successfully created.'
    redirect_to @order
  else
    @order_number = "SL-#{Time.now.to_i}"
    render :action => "new"
  end
end

应用/视图/订单/ new.html.haml:

%h1 New order
- form_for @order do |order_form| 
  = error_messages_for :order
  %p
    = order_form.label :order_number
    %br
    = text_field_tag '', @order_number, :disabled => true, :id => 'order_number_display'
    = order_form.hidden_field :order_number, :value => @order_number
  - order_form.fields_for :customer do |customer_form| 
    %p
      = customer_form.label :first_name
      %br
      = customer_form.text_field :first_name
    %p
      = customer_form.label :last_name
      %br
      = customer_form.text_field :last_name
    %p
      = customer_form.label :phone
      %br
      = customer_form.text_field :phone
    %p
      = customer_form.label :email
      %br
      = customer_form.text_field :email
  %p= order_form.submit 'Create Order'
= link_to 'Back', orders_path

2 个答案:

答案 0 :(得分:2)

使用accepts_nested_attributes_for for nest模型的属性将在params中传递,其中包含键:model(s)_attributes in case case:params[:order][:customer_attributes]

因为accept_nested_attributes_for在一对多关系的belongs_to方面工作,所以你将不得不做一些额外的工作。通过覆盖调用accept_nested_attributes_for时创建的customer_attributes attr_writter。

简而言之,这应该有效,或者至少可以帮助你解决这个问题:

class Order < ActiveRecord::Base
  accepts_nested_attributes_for :customer
  belongs_to :customer


  def customer_attributes_with_existence_check=(attributes)
    self.customer = Customer.find_by_email(attributes[:email])
    self.customer_attributes_without_existence_check=(attributes) if customer.nil?
  end

  alias_method_chain 'customer_attributes=', :existence_check

end

答案 1 :(得分:0)

添加

update_only => true 

accepts_nested_attributes_for :[model]

每次都不会破坏嵌套模型。