我有一个关于Ruby中的某个数据模型的问题。我有一组业务需求:
用户可以创建多个研讨会
用户可以参加多个研讨会
车间只有一个所有者(用户)
研讨会有许多与会者(用户)
此关系的第一部分很容易设置:
#user.rb
class User < ActiveRecord::Base
has_many :workshops
end
#workshop.rb
class Workshop < ActiveRecord::Base
belongs_to :user
end但是我如何建立从研讨会到用户的"other has_many“关系呢?我可以做一些类似研讨会的事情吗? belongs_to :user,:as :owner。研讨会has_many :users,:as :attendees?
你对此有何感想?更糟糕的是,研讨会有一个与会者限制,所以我需要验证...
谢谢,丹尼尔
发布于 2012-06-28 04:38:00
您有一个has_many到has_many的关系,因此您需要创建一个新的关联表来关联这些关系(让我们称之为attendances):
创建数据库迁移:
rails g模型出席率
然后在你的迁移中做一些类似的事情:
create_table :attendances do |t|
t.integer :attendee_id
t.integer :workshop_id
end
add_index :attendances, :attendee_id
add_index :attendances, :workshop_id
add_index :attendances, [:workshop_id, :attendee_id]现在,您有了一个表,您可以在其中将许多与会者与许多研讨会相关联。
现在,在您的用户模型中:
has_many :attending, through: :attendances, foreign_key: 'attendee_id', class_name: 'Workshop', source: :workshop在您的研讨会模型中:
has_many :attendees, through: :attendances, class_name: 'User', source: :attendee 因此,现在'some_user.attending‘将返回some_user参加的所有研讨会的ActiveRecord关系,而'some_workshop.attendees’将为您提供所有参加some_workshop的用户。
https://stackoverflow.com/questions/11231486
复制相似问题