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

时间:2010-01-02 19:39:52

标签: ruby-on-rails

完成铁杆新手试图开始。

我有两个课程,即成分和单元。有三个单位,磅,加仑和几十个,每个成分只有一个单位。我想我已正确设置了关联/路由。 在创建新配料时,我需要用户从这三个设置单位。 我用了另一个问题来解决这个问题:Drop Down Box - Populated with data from another table in a form - 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

新成分:

<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

我在RoR中只有三天深,所以我怀疑它很简单!

3 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:0)

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

class Ingredient < ActiveRecord::Base
  has_one :unit
end

class Unit < ActiveRecord::Base
  belongs_to :ingredient
end

答案 2 :(得分:-2)

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

YouAppName::Application.routes.draw do

  resources :ingredients

  resources :units

end