dan*_*per 4 ruby many-to-many ruby-on-rails ruby-on-rails-3
嗨,大家好!只有两个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 |
Run Code Online (Sandbox Code Playgroud)
问题是,用户可以确认他们是否存在于事件中,为此我使用了表Events_Users,确认了列(确认为1).如何在没有模型"Event_User"的情况下使用Rails ActiveRecord执行此操作?如何操作用户模型中的已确认列?
我正在使用Rails 3.2.9
User
并且Event
有many-to-many
关系,你不能只用2个模型建立这个关联,你必须有连接模型,或连接表.
在您的情况下,您添加了属性confirmed
,因此您将需要一个名为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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2877 次 |
最近记录: |