在我的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
单个用户可以在多个存储桶中,我们可以将多个存储桶附加到事件中。
我在这里遇到的一个问题是,在将该桶添加到事件后,我从桶中添加/删除用户时,它无法正常工作。我的意思是在使用不反映更改的特定存储桶创建事件后,存储桶中的任何更新。
我尝试在 Bucket 模型中使用 after_add 回调,但仍然遇到同样的问题。
我还应该做些什么来解决这个问题?我在这里缺少什么?
答案 0 :(得分:0)
不是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
,除非您在那里保存了大量信息,在这种情况下,您应该更改其余的建模。