Search code examples
ruby-on-railsrails-activerecordentity-relationship

displaying value from a many to many relationship


im attempting to display a value from a many to many relationship

in my view im calling the following

schedule.opponents.name

this code isnt displaying any errors, though its just displaying the word 'Opponent'

on other methods that i have a belongs_to relationship this method seems to have displayed the value i am after

any tips?

class Opponent < ActiveRecord::Base
  has_many  :schedules
  has_many  :teams
  attr_accessible :name
end


class Schedule < ActiveRecord::Base
  has_and_belongs_to_many :opponents
  has_many :teams
  attr_accessible :location_id, :date, :opponent_id, :time, :for, :against, :event, :team, :home_or_away

Solution

  • When you do a has_and_belongs_to_many relashionship, you are assuming to have n models to n models. So when you are doing a schedule.opponents, you are retrieving and array of objects of Opponent model, and because of that, you can't call an attribute of that model.
    An easy way to see the problem is to type on your console:

    schedule.opponents.last.name