【问题标题】:How to set up a 'through' model in Ruby on Rails如何在 Ruby on Rails 中设置“通过”模型
【发布时间】:2017-11-11 16:43:27
【问题描述】:

我正在尝试使用“person”模型、“event”模型和“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

当我尝试在 person 模型中显示一个条目,并在我的 people_controller.rb 文件中突出显示一行时:

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

它突出显示的行是@events = @people.events 作为问题,但我似乎无法弄清楚我做错了什么。

任何指针都非常感谢。

谢谢

【问题讨论】:

    标签: ruby-on-rails model controller


    【解决方案1】:

    您在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
    

    我希望 EventPerson 继承自 ApplicationRecord,而不是 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
    

    【讨论】:

    • 非常感谢您。我是所有这些 MVC/ruby on rails 东西的新手,所以一直在努力掌握命名约定的单一性/多重性。我已经进行了您建议的更改,并得到了一个新的有趣错误:Mysql2::Error: Unknown column 'event_people_events.person_id' in 'where clause': SELECT events.* FROM events` INNER JOIN events event_people_events ON events.id = event_people_events.event_id WHERE @9876534 @.person_id = 6`
    • 它正在寻找一个名为 event_people_events 的表,这是错误的,我猜测是由于某处的命名问题。但是在哪里?
    • 我想通了:class EventPerson &lt; Event 必须是 class EventPerson &lt; ApplicationRecord
    • 是的,我也发现了这一点。并添加它来回答。 (抱歉,正在后台进行一些调试。)
    • 非常感谢您的帮助。真的很棒的答案。