ruby-on-rails - 相同 2 个模型之间的多个 has_many/belongs_to

标签 ruby-on-rails ruby activerecord ruby-on-rails-4

我很好奇这是如何工作的...我在相同的两个模型之间有几个 has_many 关系。这是一个日历应用程序,因此可以邀请用户参加事件,用户可以参加事件,并且事件属于用户,以便查看谁创建了事件。

用户.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

事件.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.rbinvite.rb 中控制。

所以...这按预期工作。用户在参加事件时有事件。我做了一些调整,并意识到这是列表中最后检查的内容。因此,如果我将邀请移动到底部,那么当我执行类似 User.find(1).events 的操作时,就会检查这些内容。

有没有更好的方法来解决这个问题?我觉得这只是自找麻烦,不是吗?

最佳答案

当我之前这样做时,我只是将关系的名称更改为更独特的名称,然后通过 class_name 告诉 has_many 要查看的类>。您可能还必须在这些已更改的关系上添加 foreign_key 参数,以便 SQL 知道要匹配哪个键。

基本思路是:

用户.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

事件.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

关于ruby-on-rails - 相同 2 个模型之间的多个 has_many/belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19938750/

相关文章:

ruby-on-rails - wicked_pdf : footer height/styling

mysql - 在 ruby​​ 脚本上使用事件记录和 mysql

ruby - 我可以使用 AREL/ActiveRecord 更优雅地编写此查询吗?

ruby-on-rails-3 - Rails 3 ActiveRecord API - 更改查询以与 Rails 3 配合使用

ruby-on-rails - 如何修复“致命的 :unable to look up https (port 9418) (No such host is known)

ruby-on-rails - 基本的 React 元素在带有 webpack 的 Rails 5.1 中不显示

ruby-on-rails - 如何在Rails的表格中计算唯一值?

Ruby rspec 实时输出

ruby-on-rails - 如何测试这个 CSV 导入 rake 任务?

ruby-on-rails - ElasticSearch在生产环境中的行为有所不同