2017-11-11 189 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