ここに私のスキーマがあります:
Participant =
id: int
user_id: int
program_id: int
... other fields
end
User =
id: int
name: text
... other fields
end
Program =
id: int
user_id: int # this is the manager of the program
end
だから、英語で:
- ユーザーは人です。
- プログラムはユーザーによって管理されます。
- プログラムには一連の参加者もあり、それぞれがユーザーです
Rails では次のようになります。
class Participant
belongs_to :user
belongs_to
end
class User
has_many :programs
has_many :participants
end
class Program
has_many :participants
belongs_to :user
end
ユーザーが実際に has_many のプログラム (ユーザーが管理するプログラム) と、参加者を介した has_many のプログラム (ユーザーが参加するすべてのプログラム) であることに注意してください。
私が望むのは、次のように言えるようになることです。
- a_user.manages_programs
- a_user.participates_in_programs
したがって、ユーザー has_many プログラムの 2 つのフレーバーがあります。:through、:as、:class、またはそれらの線に沿った何かの魔法の組み合わせを行う必要がありますが、今のところ理解できません。
この例に続く 1 つの追加の質問。私は今持っています
class User
has_many :participations, class_name: "Participant"
has_many :moderated_programs, class_name: "Program", foreign_key: 'moderator_id'
has_many :participating_programs, through: :participations, class_name: "Program", source: :program
end
class Participant
belongs_to :user
belongs_to :program
end
3 行目に注目してください。私が望むのは、この一連の関連付けを利用することです。参加者には user_id と program_id があります。u1.participating_programs と言って、このユーザーが参加している 1 つまたは複数のプログラムのリストを取得できるようにしたいのですが、上記は機能しません。私が基地から離れている場所を教えてもらえますか?