Rails 中带有额外列的多对多表

2024-04-24

是否可以仅使用两个 Rails 模型(用户和事件)来做到这一点:

Users
|id        |name         |age         |
|1         |danilo       |26          |
|2         |joe          |23          |
|3         |carlos       |50          |
|4         |katy         |45          |

Events_Users
|event_id     |user_id        |confirmed       |
|1            |1              |1               |
|3            |3              |0               |
|4            |3              |1               |
|2            |3              |1               |

Events
|id           |name                     |date            |
|1            |the end of the year      |31/12/2012      |
|2            |the end of the world     |21/12/2012      |
|3            |Party                    |18/12/2012      |
|4            |Dinner                   |19/12/2012      |

问题是,用户可以确认自己是否存在于 事件,为此我使用了表 Events_Users,列已确认(1 表示 确认的)。在没有模型的情况下如何使用 Rails ActiveRecord 做到这一点 “事件_用户”?如何操作用户中的确认列 模型?

我正在使用 Rails 3.2.9 。


User and Event have many-to-many关系,你不能只用2个模型建立这个关联,你必须有连接模型,或者连接表。

在您的情况下,您添加了属性confirmed,所以您将需要一个名为的连接模型确认(正如其他人推荐的那样)。您定义的关联将如下所示:

class User
  has_many :events, through: :confirmations
  has_many :confirmations
end

class Event
  has_many :users, through: :confirmations
  has_many :confirmations
end

class Confirmation
  belongs_to :user
  belongs_to :event
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 中带有额外列的多对多表 的相关文章

随机推荐