我很好奇这是如何工作的...我在同一个两个模型之间有几个has_many关系。这适用于日历应用,因此可以邀请用户参加活动,用户可以参加活动,并且活动属于用户,以便查看谁创建了活动。
user.rb
class User < ActiveRecord::Base
has_many :invites, dependent: :destroy
has_many :events, through: :invites
has_many :events
has_many :attendances, -> { where cancel: false },
dependent: :destroy
has_many :events, -> { where "attendances.cancel" => false },
through: :attendances
event.rb
class Event < ActiveRecord::Base
has_many :invites, dependent: :destroy
has_many :users, through: :invites
belongs_to :user
has_many :attendances, -> { where cancel: false },
dependent: :destroy
has_many :users, -> { where "attendances.cancel" => false },
through: :attendances
我还有相应的联接表,在各自的模型中进行控制,attendance.rb
和invite.rb
。
所以...这可以按预期工作。用户在参加活动时有活动。我做了一些调整,并意识到这是检查列表中的最后一件事。所以,如果我将邀请移到底部,那么当我执行类似User.find(1).events
的操作时,就会检查这些内容。
还有更好的方法吗?我觉得这只是在惹麻烦,不是吗?
答案 0 :(得分:2)
当我之前完成此操作时,我刚刚将关系名称更改为更独特的名称,然后告诉has_many
通过class_name
查看哪个类。您可能还必须在这些已更改的关系上添加foreign_key
参数,因此SQL知道要匹配哪个键。
这是基本想法:
user.rb
class User < ActiveRecord::Base
has_many :invites, dependent: :destroy
has_many :invited_events, through: :invites, source: "Event"
has_many :events # these are events "owned" by the user
has_many :attendances, -> { where cancel: false }, dependent: :destroy
has_many :attended_events, -> { where "attendances.cancel" => false }, through: :attendances, source: "Event"
end
event.rb
class Event < ActiveRecord::Base
has_many :invites, dependent: :destroy
has_many :invitees, through: :invites, source: "User"
belongs_to :user # this is the owner of the event
has_many :attendances, -> { where cancel: false }, dependent: :destroy
has_many :attendees, -> { where "attendances.cancel" => false }, through: :attendances, source: "User"
end