2017-11-11 239 views
1

我正在尝试使用'person'模型,'event'模型和'event_person'模型创建应用程序,以存储人们参加的细节哪些事件。如何在Ruby on Rails中设置'through'模型

我已经设置好了,所以每个人都有很多事件,它们通过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作为问题的线路,但我似乎无法到弄清楚我做错了什么。

任何指针非常赞赏。

感谢

回答

2

你在Person失踪has_many :event_people

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 

我希望EventPersonApplicationRecord继承,而不是Event 。而且,peopleevents要以它们的单数形式,比如?

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 
+0

非常感谢你这样做。作为所有这些MVC/ruby​​ on rails的新手,所以一直在努力克服单点/多个命名约定。我做了你所建议的更改,并得到一个新的有趣的错误:''where'子句'中的Mysql2 :: Error:未知列'event_people_events.person_id':SELECT'events'。* FROM'events' INNER JOIN'events'' event_people_events' ON'' events'.''''''event_people_events'''event_id' WHERE'event_people_events'.'person_id' = 6' –

+0

它寻找一个名为event_people_events的表,它是错误的,我猜是由于某处的命名问题。但是哪里? –

+0

我想出来了:'class EventPerson