2010-01-03 3 views
12

Une autre question de débutant.has_many méthode de construction, Rails

Objectif: chaque ingrédient peut avoir zéro ou plusieurs conversions d'unités liées. Je veux mettre un lien pour créer une nouvelle conversion d'unité sur la page qui montre un ingrédient spécifique. Je n'arrive pas à le faire fonctionner.

Modèle Ingrédients:

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

Unité Modèle de conversion:

class UnitConversion < ActiveRecord::Base 
    belongs_to :Ingredient 
end 

Controller Conversion (pour nouvelle)

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 

Routes pertinentes:

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

Afficher des ingrédients Lien:

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

Ceci est l'erreur:

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' 

Aide! Je suis tout mélangé à ce sujet.

Répondre

23

Unité Contrôleur de conversion pour new et create devrait être:

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 

En outre, ce screencast est une belle ressource pour les ressources imbriquées.

5
has_many :unit_conversion 

Faut-il Pluralisé depuis que vous appelez avec

@unit_conversion = @ingredient.unit_conversions.build 

votre contrôleur

def new 
    @ingredient = Ingredient.all 

devrait appeler #new installer un nouvel ingrédient ou #find pour saisir un ingrédient existant.

@ingredient = Ingredient.new  # returns a new Ingredient 

ou

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

Lequel vous choisissez est à vos besoins.

Aussi, c'est une faute de frappe, non?

belongs_to :Ingredient 

Vous voudrez peut-être en minuscules :ingredient