2010-01-03 50 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