0

I have show action in the Exhibitor model. I want to display a list of Meetings for which the Exhibitor is a Sponsor.

Exhibitor model:

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 action:

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 view:

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

When I run the page I get this:

NoMethodError in Exhibitors#show

undefined method `each' for # Rails.root: C:/RailsInstaller/Ruby1.9.3/eventmanager

Application Trace | Framework Trace | Full Trace app/controllers/exhibitors_controller.rb:17:in `show' Request

Parameters:

{"id"=>"1"} Show session dump

What am I doing wrong on the controller page to keep getting this error?

Konrad Gadzina
  • 3,407
  • 1
  • 18
  • 29

1 Answers1

0

The error is connected with @sponsoredmeetings.each in your view.

@sponsoredmeetings has value of @exhibitor.sponsor, and sponsor attribute, as I can see in your model, is not something returning collection but a single object, so there is no each method for object returned by this attribute. You have belongs_to connection from exhibitor to sponsor, so one exhibitor belongs to only one sponsor.

If you would like to create one to many relationship, where one exhibitor has many sponsors, you should replace

belongs_to :sponsor

with

has_many :sponsors

If you want many to many relationship (many exibitior has many sponsors and sponsor has many exhibitors), check has_and_belongs_to_many connection described in this question.

Of course, if your database schema has one to many relationship, where one sponsor has many exhibitors (as your exhibitor model suggests) and you want to change your models in one of proposed ways, remember to update relationships in database.

Be sure to read more about associations in rails.

Community
  • 1
  • 1
Konrad Gadzina
  • 3,407
  • 1
  • 18
  • 29