简体   繁体   中英

How to set up a 'through' model in Ruby on Rails

I am trying to create an app with a 'person' model, and 'event' model and an 'event_person' model to store the details of which people are attending which events.

I have set this up so there are many events for each person, which relate through the event_person model. However, I am getting an error when running the app and I can't understand what I have done wrong.

Person model:

class Person < ActiveRecord::Base
belongs_to :team
has_many :events, through: :event_people
validates :first_name, presence: true, length: { maximum: 255 }
validates :last_name, presence: true, length: { maximum: 255 }
validates :email, presence: true, length: { maximum: 255 }
scope :ards,  ->{ where("team_id = ?",2)}
end

Event model:

class Event < ApplicationRecord
belongs_to :people
validates :name, presence: true
end

Event_person model:

class EventPerson < Event
belongs_to :people
belongs_to :events
#accepts_nested_attributes_for :events, :people
validates :role, presence: true, length: { maximum: 20 }
end

The error I get is

Could not find the association :event_people in model Person

when I try and show an entry in the person model, and highlights a line in my people_controller.rb file:

 def show
    @people = Person.find(params[:id])
    @events = @people.events
end

The line it highlights is @events = @people.events as the problem, but as I can't seem to figure out what I have done wrong.

Any pointers much appreciated.

Thanks

You're missing has_many :event_people on Person :

class Person < ActiveRecord::Base
  ...
  has_many :event_people
  has_many :events, through: :event_people
  ...
end

Also, this seems all munged up:

class EventPerson < Event
  belongs_to :people
  belongs_to :events
  ...
end

I would expect EventPerson to inherit from ApplicationRecord , not Event . And, people and events to be in their singular form, like?

class EventPerson < ApplicationRecord
  belongs_to :person
  belongs_to :event
  ...
end

I don't really know what you're trying to do with people , here:

class Event < ApplicationRecord
  belongs_to :people
  ...
end

Perhaps you actually meant:

class Event < ApplicationRecord
  has_many :event_people
  has_many :people, through: :event_people
  ...
end

Also, it's a little weird to say @people = Person.find(params[:id]) here:

def show
  @people = Person.find(params[:id])
  @events = @people.events
end

Because Person.find(params[:id]) is going to return a single record, not a collection of records. I would expect to see:

def show
  @person = Person.find(params[:id])
  @events = @person.events
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM