2010-01-03 18 views
12

Otra pregunta para principiantes.has_many build method, Rails

El objetivo: cada ingrediente puede tener cero o más conversiones de unidades asociadas. Quiero poner un enlace para crear una nueva conversión de unidad en la página que muestre un ingrediente específico. No puedo hacer que funcione.

Ingrediente Modelo: Conversión

class Ingredient < ActiveRecord::Base 
    belongs_to :unit 
    has_many :unit_conversion 
end 

Unidad Modelo:

Controlador de conversión
class UnitConversion < ActiveRecord::Base 
    belongs_to :Ingredient 
end 

unidad (nueva)

def new 
    @ingredient = Ingredient.all 
    @unit_conversion = @ingredient.unit_conversions.build(params[:unit_conversion]) 
    if @unit_conversion.save then 
     redirect_to ingredient_unit_conversion_url(@ingredient, @comment) 
     else 
      render :action => "new" 
     end 
    end 

Rutas pertinentes:

map.resources :ingredients, :has_many => :unit_conversions 

Mostrar Ingrediente Enlace:

<%= link_to 'Add Unit Conversion', new_ingredient_unit_conversion_path(@ingredient) %> 

Este es el error:

NoMethodError in Unit conversionsController#new 

undefined method `unit_conversions' for #<Array:0x3fdf920> 

RAILS_ROOT: C:/Users/joan/dh 
Application Trace | Framework Trace | Full Trace 

C:/Users/joan/dh/app/controllers/unit_conversions_controller.rb:14:in `new' 

Ayuda! Estoy todo mezclado sobre esto.

Respuesta

23

Controlador de conversión de unidades para new y create debería ser:

def new 
    @ingredient = Ingredient.find(params[:ingredient_id])  
    @unit_conversion = @ingredient.unit_conversions.build 
end 

def create 
    @ingredient = Ingredient.find(params[:ingredient_id])  
    @unit_conversion = @ingredient.unit_conversions.build(params[:unit_conversion]) 

    if @unit_conversion.save 
    flash[:notice] = "Successfully created unit conversion." 
    redirect_to ingredient_unit_conversions_url(@ingredient) 
    else 
    render :action => 'new' 
    end 
end 

Además, este screencast es un buen recurso para los recursos anidados.

5
has_many :unit_conversion 

En caso de ir en plural, ya que está llamando con

@unit_conversion = @ingredient.unit_conversions.build 

su controlador

def new 
    @ingredient = Ingredient.all 

debe llamar #new de configurar un nuevo ingrediente o #find para agarrar un ingrediente existente.

@ingredient = Ingredient.new  # returns a new Ingredient 

o

@ingredient = Ingredient.find(...) # returns an existing Ingredient 

Que uno elige depende de sus necesidades.

Además, esto es un error tipográfico, ¿verdad?

belongs_to :Ingredient 

Es posible que desee a minúsculas :ingredient

Cuestiones relacionadas