Ruby on Rails调用object.each时出现NoMethodError

时间:2013-02-11 00:26:05

标签: ruby-on-rails nomethoderror

我在show模型中有Exhibitor个动作。我想显示MeetingsExhibitor Sponsor的{​​{1}}列表。

Exhibitor型号:

class Exhibitor < ActiveRecord::Base
 attr_accessible :description, :name, :exhibitor_category, :sponsor,    :exhibitor_category_id

 validates :name, :presence => true
 validates :description, :presence => true
 validates :exhibitor_category, :presence => true

 belongs_to :exhibitor_category
 belongs_to :sponsor
 end

show行动:

def show
    @exhibitor = Exhibitor.find(params[:id])
    @sponsoredmeetings = @exhibitor.sponsor

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @exhibitor }
    end
  end

show查看:

    <p>
    <b>Meetings:</b>
    <% @sponsoredmeetings.each do |c| %>
    <%= c.meetings %>
    <% end %>
    </p>

当我运行页面时,我得到了这个:

  

参展商中的NoMethodError#show

     

#Rails.root的未定义方法`each':   C:/RailsInstaller/Ruby1.9.3/eventmanager

     

应用程序跟踪|框架跟踪|完整追踪   app / controllers / exhibitors_controller.rb:17:在'show'Request

中      

参数:

     

{“id”=&gt;“1”}显示会话转储

我在控制器页面上做错了什么来继续收到此错误?

1 个答案:

答案 0 :(得分:0)

错误与您视图中的@sponsoredmeetings.each相关联。

@sponsoredmeetings的值为@exhibitor.sponsorsponsor属性,正如我在模型中看到的那样,不是返回集合而是单个对象,因此没有{{1此属性返回的对象的方法。您从eachbelongs_toexhibitor个连接,因此一个 sponsor仅属于一个 exhibitor }。

如果您想创建一对多的关系,一个参展商有很多赞助商,您应该更换

sponsor

belongs_to :sponsor

如果您想要多对多的关系(许多exibitior有很多赞助商,赞助商有很多参展商),请检查this question中描述的has_many :sponsors 连接。

当然,如果您的数据库架构有一对多的关系,其中一个赞助商有很多参展商(正如您的has_and_belongs_to_many模型建议的那样)并且您想要以一种建议的方式更改模型,请记住更新关系在数据库中。

请务必详细了解associations in rails

相关问题