複数のモデルとの関連付けが多い
概要
3つのモデルがあります ユーザーテーブルの属性は、name:string、age:integer、kind:integer です。 登録テーブルの属性は、user_id:integer、tutor_id:integer、event_id:integer、favorite:boolean です。 イベント テーブルの属性は name:string です。 ここで、ユーザーの種類は学生、チューター、またはチューター_スチューデントになります。
# user.rb
class User < ApplicationRecord
enum kind: { student: 0, tutor: 1, tutor_student: 2 }
has_many :registrations
has_many :tutors, through: :registrations
has_many :favorites, -> { where(registrations: { favorite: true }) }, through: :tutors, source: :event, class_name: 'Event'
end
# Event.rb
class Event < ApplicationRecord
has_many :registrations, foreign_key: :program_id
has_many :users, through: :registrations
has_many :tutors, through: :registrations
end
# registration.rb
class Registration < ApplicationRecord
belongs_to :user
belongs_to :tutor, class_name: 'User'
belongs_to :event
end
ここが問題です
私が与えた上記のダミーデータサンプルのような多くの関係を介して、ユーザーイベントのお気に入りの講師を取得しようとしています
user.tutors.favorites
しかし、このエラーが発生します
undefined method `favorites' for #<User::ActiveRecord_Associations_CollectionProxy:0x00007f04e8a7b540>
誰か私の関連付けを修正するのを手伝ってくれませんか。
解決策
発生しているエラーに関して、未定義のメソッドが発生する理由は、技術的には単一のユーザーではなくユーザーのコレクションに対して .favorites を呼び出しているためです。
次のようなものを使用すると、ユーザーの講師のお気に入りにアクセスできます。
user.tutors.joins(:registrations).where(registrations: {favorite: true})