2010-01-02 83 views
4

完整的rails新手试图开始。Rails:成分的未定义方法`map'

我有两个类,成分和单位。有三个单位,磅,加仑和几十个,每种成分只有一个单位。我想我已经正确设置了关联/路线。 创建新配料时,我需要用户从这三个设置单位。 我用另外一个问题远来得到这样的:对于单位

class Ingredient < ActiveRecord::Base 
    belongs_to :unit 
end 

产品型号:用于配料Drop Down Box - Populated with data from another table in a form - Ruby on Rails

型号

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 

主料新视角:

<h1>New ingredient</h1> 

<% form_for(@ingredient) do |f| %> 
    <%= f.error_messages %> 

    <p> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </p> 
    <p> 
    <%= f.label :needsDefrosting %><br /> 
    <%= f.check_box :needsDefrosting %> 
    </p> 
    <p> 
    <%= f.label :baseName %> 
    <%= f.collection_select :unit_id, @ingredient, :id, :baseName, :prompt => "Select a Base Measurement"%> 
    <br /> 
    </p> 
    <p> 
    <%= f.submit 'Create' %> 
    </p> 
<% end %> 

<%= link_to 'Back', ingredients_path %> 

的错误是

NoMethodError in Ingredients#new 

Showing app/views/ingredients/new.html.erb where line #16 raised: 

undefined method `map' for #<Ingredient:0x3dae1c0> 

Extracted source (around line #16): 

13: </p> 
14: <p> 
15: <%= f.label :baseName %> 
16: <%= f.collection_select :unit_id, @ingredient, :id, :baseName, :prompt => "Select a Base Measurement"%> 
17: <br /> 
18: </p> 
19: <p> 

RAILS_ROOT: C:/Users/joan/dh 

我在回报率只有三天左右深,所以我怀疑它的简单!

回答

6

collection_select需要一个选项数组,您传递一个成分。将@ingredient更改为Unit.all应该可以修复它。

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

作为一个侧面说明,如果你永远只能将有3种类型的单位,可能更有意义,创造,而不是具有单位表常数。这将减少连接的数量,并使整体模型更简单一些。

0

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

class Ingredient < ActiveRecord::Base 
    has_one :unit 
end 

class Unit < ActiveRecord::Base 
    belongs_to :ingredient 
end 
+0

但是,从文档/读取我的印象,是,如果你使用HAS_ONE,则每次我添加一个新的成分,我也添加一个新的单位。我不想要这个。只有三个单位,我只需要每个成分与一个单元相关联? – Joan 2010-01-02 20:10:15

+0

'has_one'关联可以做到这一点。 – 2010-01-03 10:09:33

-2

如果您在轨是3应用程序,路由文件应该是这样的

YouAppName::Application.routes.draw do 

    resources :ingredients 

    resources :units 

end 
相关问题