mysql - 事件记录。包括来自连接表的数据

标签 mysql ruby-on-rails ruby activerecord

(最好是 Ruby/Rails 大师 :P)

我有一个有趣的问题。希望它还没有回答(等等,是的,我回答了!)但我已经看过但找不到它。 (希望不是,因为这是不可能的)

我有两个类(我想保持这种状态)组和事件(见下文)。

class Group < ActiveRecord::Base
    has_and_belongs_to_many :events
end

但是在我的连接表 (group_events) 中,我有额外的列为事件提供情有可原的情况……我希望此信息在事件对象上可用。 (例如,是否必须出席等)

我的第二个稍微相关的问题是,我能否不执行以下操作:

class Event < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class GroupEvent < Event
    # Implies that a GroupEvent would be an Event, with all the other attributes of the group_events table minus the
    # two id's (group_id, event_id) that allowed for its existence (those would just be references to the group and event object)
end

最佳答案

我会先重写 has_and_belongs_to_many ,明确描述了 Event 之间的关系和 GroupEvent 的模型.

class Group < ActiveRecord::Base
  has_many :group_events
  has_many :events, :through => :group_events
end

class Event < ActiveRecord::Base
  has_many :group_events
  has_many :groups, :through => :group_events
end

class GroupEvent < ActiveRecord::Base
  belongs_to :group
  belongs_to :event
end

然后您可以在 Event 中使用方法类来引用您之后的 GroupEvent 属性。对于一些 bool 值 :attendance_mandatory GroupEvent 中的属性,你可以做类似的事情

class Event < ActiveRecord::Base
  has_many :group_events
  has_many :groups, :through => :group_events

  def attendance_mandatory?(group)
    group_events.find(group.id).attendance_mandatory?
  end
end

与一些 Event作为e和相关Group作为g , 你现在可以做

e.attentdance_mandatory?(g)

关于你的第二个问题,我想你正在寻找我在上面第一个代码块中发布的内容的一部分。

class GroupEvent < ActiveRecord::Base
  belongs_to :group
  belongs_to :event
end

每个包含您希望与之交互的数据的表在您的应用程序中都应该有一个代表性模型。以上符合您规定的标准(公开了 GroupEvent 的属性)

注意: class GroupEvent < Event 的语法用于 Single Table Inheritance (您会将 attendance_mandatory 之类的属性移动到 events 表中,并将该 events 表用于常规 EventGroupEvent - 尽管这超出了本文的范围问题)

关于mysql - 事件记录。包括来自连接表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387242/

相关文章:

mysql - 如何使用 MySQL 数据库中的值填充 Sencha Touch 2 中的列表

ruby-on-rails - (Ruby,Rails)模块和库中 SELF 的上下文......?

ruby-on-rails - 用 ruby​​ 完成的基于网络的游戏,为我指明了正确的方向

ruby-on-rails - 使用部分,如何以 DRY 方式呈现 `striped` 表行?

ruby-on-rails - Product has_one状态和状态机作用于association的场景下如何为rspec测试添加种子数据

ruby - 查看 USB 设备是否已连接。 Linux 中的 ruby

java - Hibernate 用 NULL 覆盖列值?

python - 使用 SQLAlchemy 在不经常使用的 Python/Flask 服务器上避免 "MySQL server has gone away"

java - 无法连接到 MySQL 服务器

ruby - 尝试通过 SSL 创建一个简单的 Ruby 服务器