2010-01-03 49 views
12

另一個新手問題。has_many構建方法,Rails

目標:每種成分可以有零個或多個與之相關的單位轉換。我想要在頁面上放置一個鏈接來創建新的單位轉換,以顯示特定的成分。我無法完成它的工作。

成分型號:

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

單位轉換型號:

class UnitConversion < ActiveRecord::Base 
    belongs_to :Ingredient 
end 

單位轉換控制器(新)

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 

相關途徑:

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

展會成份鏈接:

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

這是錯誤:

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' 

幫助!我都混淆了這一點。爲newcreate

回答

23

單位轉換器應該是:

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 

此外,這screencast是嵌套資源一個很好的資源。

5
has_many :unit_conversion 

如果因爲你與

@unit_conversion = @ingredient.unit_conversions.build 

控制器

def new 
    @ingredient = Ingredient.all 

應該呼籲#new設置一個新的成分或#find抓住現有的成份稱它可以使用複數。

@ingredient = Ingredient.new  # returns a new Ingredient 

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

你選擇哪一個達到您的要求。

此外,這是一個錯字,對嗎?

belongs_to :Ingredient 

您可能要小寫:ingredient