Ruby on rails Rails中具有额外列的多对多表
仅使用两个Rails模型(用户和事件)就可以做到这一点:Ruby on rails Rails中具有额外列的多对多表,ruby-on-rails,ruby,ruby-on-rails-3,many-to-many,Ruby On Rails,Ruby,Ruby On Rails 3,Many To Many,仅使用两个Rails模型(用户和事件)就可以做到这一点: Users |id |name |age | |1 |danilo |26 | |2 |joe |23 | |3 |carlos |50 | |4 |katy |45 | Events_Users |
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\u Users,列confirm(1表示
确认)。在没有模型的情况下,如何使用Rails ActiveRecord实现这一点
“事件用户”?如何操作用户界面中的“已确认”列
模特儿
我使用的是Rails 3.2.9。而不是用户模型,与
has_and_belongs_to_many :events
并修改用户的联接表事件(有点脏)
最好使用具有两个所属关系的模型确认:
belongs_to :user
belongs_to :event
我希望这能帮助你,
Alessandro
用户
和事件
具有多对多
关系,您不能仅使用2个模型设置此关联,您必须具有联接模型或联接表
在您的例子中,您添加了属性Confirmation
,因此需要一个名为Confirmation的连接模型(如其他人所建议的)。您的定义关联如下所示:
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
由于联接表上有额外的字段,因此需要联接模型。看看这个:
class User
has_many :invitations
has_many :invited_events, -> {where(confirmed: false)}, class_name: 'Event', through: :invitations
has_many :confirmed_events, -> {where(confirmed: true)}, class_name: 'Event', through: :invitations
end
class Event
has_many :invitations
has_many :invited_users, -> {where(confirmed: false)}, class_name: 'User', through: :invitations
has_many :confirmed_users, -> {where(confirmed: true)}, class_name: 'User', through: :invitations
end
class Invitation
belongs_to :user
belongs_to :event
end
这样,
user.confirmed\u events
将仅在联接表中将confirmed标志设置为true时提供用户的事件。这个问题解决了您的问题吗?我认为最优雅的解决方案是你拥有的。用户有_many:events\u users(我会将events\u users重命名为“Confirmation”),一个事件有_many:users,:through=>confirmations。感谢Alessandro的回答!你是对的,但基恩的答案更完整。非常感谢你!