我正在尝试与一个人建立一个应用程序'模特和'事件'模特和'event_person'模型存储人们参加哪些事件的详细信息。
我已经设置了这个,所以每个人都有很多事件,这些事件通过event_person模型联系起来。但是,我在运行应用程序时遇到错误,我无法理解我做错了什么。
人物模型:
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
活动模式:
class Event < ApplicationRecord
belongs_to :people
validates :name, presence: true
end
Event_person模型:
class EventPerson < Event
belongs_to :people
belongs_to :events
#accepts_nested_attributes_for :events, :people
validates :role, presence: true, length: { maximum: 20 }
end
我得到的错误是
Could not find the association :event_people in model Person
当我尝试在人物模型中显示一个条目,并在我的people_controller.rb文件中突出显示一行:
def show
@people = Person.find(params[:id])
@events = @people.events
end
它突出显示的行是问题@events = @people.events
,但我似乎无法弄清楚我做错了什么。
任何指针都非常赞赏。
由于
答案 0 :(得分:2)
您在has_many :event_people
上遗漏了Person
:
class Person < ActiveRecord::Base
...
has_many :event_people
has_many :events, through: :event_people
...
end
此外,这似乎都被提了出来:
class EventPerson < Event
belongs_to :people
belongs_to :events
...
end
我希望EventPerson
继承ApplicationRecord
,而不是Event
。并且people
和events
是单数形式的,例如?
class EventPerson < ApplicationRecord
belongs_to :person
belongs_to :event
...
end
我真的不知道你在people
尝试做什么,在这里:
class Event < ApplicationRecord
belongs_to :people
...
end
也许你的意思是:
class Event < ApplicationRecord
has_many :event_people
has_many :people, through: :event_people
...
end
另外,在这里说@people = Person.find(params[:id])
有点奇怪:
def show
@people = Person.find(params[:id])
@events = @people.events
end
因为Person.find(params[:id])
将返回单个记录,而不是记录集合。我希望看到:
def show
@person = Person.find(params[:id])
@events = @person.events
end