Rails:成分的未定义方法`map’

尝试入门的完整铁轨新手。

我有两个课程,即成分和单元。 有三个单位,磅,加仑和几十个,每个成分只有一个单位。 我想我已经正确设置了关联/路由。 在创建新配料时,我需要用户从这三个设置单位。 我用另一个问题来解决这个问题: Drop Down Box – 填充表格中另一个表的数据 – Ruby on Rails

成分模型:

class Ingredient < ActiveRecord::Base belongs_to :unit end 

单位模型:

 class Unit < ActiveRecord::Base end 

路线:

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

配料新控制器

 def new @ingredient = Ingredient.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @ingredient } end end 

成分新视图:

 

New ingredient



"Select a Base Measurement"%>

错误是

  NoMethodError in Ingredients#new Showing app/views/ingredients/new.html.erb where line #16 raised: undefined method `map' for # Extracted source (around line #16): 13: 

14:

15: 16: "Select a Base Measurement"%> 17:
18:

19:

RAILS_ROOT: C:/Users/joan/dh

我只有三天左右的RoR,所以我怀疑它很简单!

collection_select需要一系列选项,你传递的是一种成分。 将@ingredient更改为Unit.all应该修复它。

 %= f.collection_select :unit_id, Unit.all, :id, :baseName, :prompt => "Select a Base Measurement"%> 

作为旁注,如果您只有3种类型的单位,那么创建常量而不是拥有单位表可能更有意义。 这将减少连接数并使整个模型更简单一些。

根据您对成分和单位相关的描述,模型类中的关联是不正确的。 它应该是:

 class Ingredient < ActiveRecord::Base has_one :unit end class Unit < ActiveRecord::Base belongs_to :ingredient end 

如果您使用的是rails 3应用程序,则路径文件应如下所示

 YouAppName::Application.routes.draw do resources :ingredients resources :units end