多对多表,在Rails中有一个额外的列 [英] many to many table with an extra column in Rails

查看:48
本文介绍了多对多表,在Rails中有一个额外的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!仅使用两种Rails模型即可做到这一点:User和 事件:

Hi guys! Is possible to do this with only two Rails models, User and Event:

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做到这一点 "Event_User"?我该如何操作用户中的确认列 型号?

The problem is, the user can confirm or not their presence in an event, for this I used the table Events_Users, column confirmed (1 for confirmed). How can I do this with Rails ActiveRecord without an model "Event_User"? how can I manipulate the confirmed column in the User model?

我正在使用Rails 3.2.9

I'm using Rails 3.2.9

推荐答案

UserEvent具有many-to-many关系,您不能仅使用2个模型来建立此关联,必须具有联接模型,或者联接表.

User and Event have many-to-many relationship, you can not set up this association with just 2 model, you must have the join model, or join table.

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

In your case, you added attribute confirmed, so you will need a join model, named Confirmation (as other people recommended). Your define associations will be like this:

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

这篇关于多对多表,在Rails中有一个额外的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆