Ruby on Rails:未初始化的常量,NameError

时间:2018-03-23 12:18:06

标签: ruby-on-rails ruby ruby-on-rails-3

您好我正在尝试解决RAILS应用程序中的名称错误。我正在开发一个界面,该界面包含一个地图,其中的图块与一定数量的项目相关联。

我有以下型号:area.rb

class Area < ActiveRecord::Base
  attr_accessible :map_file_name, :tile_file_name, :alt, ...

  has_many :species
  has_many :maps

end

map.rb

class Map < ActiveRecord::Base
  attr_accessible :alt, :file_name, :detail, :area_id

  belongs_to :area
end

specie.rb

class Specie < ActiveRecord::Base
  attr_accessible :area_id, :author_id, :name, :pwclass, :pwfamily, :txtlandscape, :txtpod, :map

  has_one :author
  belongs_to :area

end

当我尝试在IRB或视图中调用资源时,我得到名称错误输出。我将specie更改为field,将species更改为fields,并使用相同的配置。

我检查过,Ruby将specie正确地复数为species

如何让specie工作?

更新:回溯

Started GET "/projects/show/1" for 127.0.0.1 at Fri Mar 23 13:02:07 +0100 2018
Connecting to database specified by database.yml
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"1"}
  [1m[36mArea Load (1.8ms)[0m  [1mSELECT 'areas'.* FROM 'areas' WHERE 'areas'.'id' = ? LIMIT 1[0m  [["id", "1"]]
  [1m[35mMap Load (0.4ms)[0m  SELECT 'maps'.* FROM 'maps' WHERE 'maps'.'area_id' = 1
  Rendered projects/show.html.erb (28.1ms)
Completed 500 Internal Server Error in 108ms

ActionView::Template::Error (uninitialized constant Area::Species):
    28:         end %>
    29: <% else %>
    30: <% end %>
    31: <% for specie in @area.species %>
    32: <div class="speciesmap">
    33:   <div id="tile_menu">
    34:     <a onclick="ArticleRequest('/article/show/area-07.html', 'ATLAS-06');"><img src="images/MAP/GUADALQUIVIR_MAP-BUTTONS-TILE-specie.svg" onMouseOver="this.src='images/MAP/estuario_area_136x85px-blck.svg'" onMouseOut="this.src='images/MAP/GUADALQUIVIR_MAP-BUTTONS-TILE-specie.svg'" alt="Specie"></a>
  app/views/projects/show.html.erb:31:in '_app_views_projects_show_html_erb__1608931551_2294133420'
  app/controllers/projects_controller.rb:22:in `show'


  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.6ms)
  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (40.4ms)

2 个答案:

答案 0 :(得分:1)

将您的Area类中的关系更新为:

    has_many :species, :class_name => 'Specie'

然后@area.species应该有用。

答案 1 :(得分:0)

正如@max在评论中强调的那样。这里的问题是物种“在单数和复数中是相同的”。

这两个解决方案要么使用物种作为模型名称,要么在相关模型中声明类别“specie”。

我试过了两个,两个都在工作。最后我选择了@ max的建议。