Ruby on rails 有很多构建方法,Rails

Ruby on rails 有很多构建方法,Rails,ruby-on-rails,Ruby On Rails,另一个新手问题 目标是:每种成分都可以有零个或多个单位转换。我想在显示特定成分的页面上添加创建新单位转换的链接。我不能完全让它工作 成分模型: class Ingredient < ActiveRecord::Base belongs_to :unit has_many :unit_conversion end 有关路线: map.resources :ingredients, :has_many => :unit_conversions 显示成分链接: <

另一个新手问题

目标是:每种成分都可以有零个或多个单位转换。我想在显示特定成分的页面上添加创建新单位转换的链接。我不能完全让它工作

成分模型:

class Ingredient < ActiveRecord::Base
   belongs_to :unit
   has_many :unit_conversion
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'
NoMethodError单位转换控制器#新
未定义的方法“单位转换”#
RAILS\u ROOT:C:/Users/joan/dh
应用程序跟踪|框架跟踪|完整跟踪
C:/Users/joan/dh/app/controllers/unit\u conversions\u controller.rb:14:in'new'

救命啊!关于这一点,我完全搞糊涂了。

新的和创建的单位转换控制器应该是:

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
另外,对于嵌套资源来说,这是一个不错的资源

has_many :unit_conversion
应该是多元的,因为你用

@unit_conversion = @ingredient.unit_conversions.build
你的控制器

def new
  @ingredient = Ingredient.all
应调用
#new
设置新配料或
#find
获取现有配料

@ingredient = Ingredient.new       # returns a new Ingredient

你选择哪一个符合你的要求

还有,这是个打字错误,对吗

belongs_to :Ingredient
您可能希望使用小写的
:component

@ingredient = Ingredient.new       # returns a new Ingredient
@ingredient = Ingredient.find(...) # returns an existing Ingredient
belongs_to :Ingredient