在我的 rails 4 应用程序中,我有以下模型
Class User
has_many :user_buckets
has_many :buckets, through: :user_buckets, dependent: :destroy
end
Class Bucket
has_many :user_buckets, after_add: :update_event_bucket_participants, after_remove: :update_event_bucket_participants
has_many :users, through: :user_buckets, dependent: :destroy
end
Class UserBucket
belongs_to :user
belongs_to :bucket
validates_uniqueness_of :user_id, :scope => :bucket_id
end
class Event
has_many :event_buckets
has_many :buckets, :through => :event_buckets
end
class EventBucket < ActiveRecord::Base
belongs_to :event
belongs_to :bucket
after_commit :update_event_partcipants
has_many :event_participants, dependent: :destroy
def update_event_partcipants
bucket_users = Bucket.find_by_id(self.bucket_id).users
bucket_users.each do |user|
self.event_participants.create(user_id: user.id)
end
end
end
单个用户可以位于多个存储桶中,我们可以将多个存储桶附加到一个事件。
我在这里面临的一个问题是,当我在存储桶添加到事件后从存储桶中添加/删除用户时,它无法正常工作。我的意思是创建事件后存储桶中的任何更新都不会反映更改。
我尝试在存储桶模型中使用after_add回调,但仍然遇到同样的问题。
我应该怎么做才能解决这个问题?我在这里缺少什么?
不是 100% 确定这是否有效,但如果您更改:
Bucket
似乎是Users
和Events
之间的连接模型,它可以容纳许多用户和许多事件吗?
class Bucket < ActiveRecord::Base
has_many :user_buckets
has_many :users, through: :user_buckets
has_many :event_buckets
has_many :events, through: :event_buckets
end
class User < ActiveRecord::Base
has_many :user_buckets
has_many :buckets, through: :user_buckets
has_many :events, through: :user_buckets
end
class UserBucket < ActiveRecord::Base
belongs_to :user
belongs_to :bucket
has_many :events, through: :bucket
validates :user_id, :uniqueness => { :scope => :bucket_id }
end
class Event < ActiveRecord::Base
has_many :event_buckets
has_many :buckets, through: :event_buckets
has_many :users, through: :event_buckets
end
class EventBucket < ActiveRecord::Base
belongs_to :event
belongs_to :bucket
has_many :users, through: :bucket
validates :event_id, :bucket_id, presence: true
end
这样,您可以通过执行Event.find(1).users
来获取所有用户,并且您将通过联接模型获得所有参与者。无需创建EventParticipant
,除非您在那里保存了大量信息,在这种情况下,您应该更改建模的其余部分。