2012-03-25 9 views
5

consigoRecordNotFound con accepts_nested_attributes_for y belongs_to

ActiveRecord :: RecordNotFound: No se pudo encontrar cliente con ID = 3 para una orden con ID =

cuando se trata de presentar un formulario de pedido para una Cliente existente. Esto sucede a través de la forma o la consola escribiendo:

Order.new(:client_attributes => { :id => 3 }) 

payment_form.html.erb:

<%= semantic_form_for @order, :url => checkout_purchase_url(:secure => true) do |f| %> 

     <%= f.inputs "Personal Information" do %> 

      <%= f.semantic_fields_for :client do |ff| %> 
       <%= ff.input :first_name %> 
       <%= ff.input :last_name %>    
       <!-- looks like semantic_fields_for auto-inserts a hidden field for client ID --> 
      <% end %> 

     <% end %> 
<% end %> 

Order.rb:

class Order < ActiveRecord::Base 
    belongs_to :client 
    accepts_nested_attributes_for :client, :reject_if => :check_client 

    def check_client(client_attr) 
    if _client = Client.find(client_attr['id']) 
     self.client = _client 
     return true 
    else 
     return false 
    end  
    end 
end 

La idea vino reject_if desde here pero registré el método y ¡ni siquiera se llama! ¡No importa cuál es su nombre!

Respuesta

7

ha solucionado el problema de la sobrecarga de la client_attributes = método, tal como se describe here:

def client_attributes=(client_attrs)  
    self.client = Client.find_or_initialize_by_id(client_attrs.delete(:id)) 
    self.client.attributes = client_attrs 
    end 
+0

¿No termina creando otro cliente incluso si encuentra un cliente por identificación? – dubilla

0

Si sólo desea una nueva Orden con un cliente existente, sin modificar el cliente, es necesario asignar el ID.

Order.new(client_id: 3) 

Esta es otra manera de hacer esto sin sobrecargar el método client_attributes= y más limpio

El nuevo pedido ahora tiene el cliente con ID 3

Si también desea actualizar los atributos del cliente Ant debes agregue el client_attributes, por ejemplo:

Order.new(client_id: 3, client_attributes: { id: 3, last_order_at: Time.current }) 
Cuestiones relacionadas