2016-03-13 22 views
0

在我的軌道4應用程序,我有以下型號更新在父母一方子模型以觸發另一個模型變更軌道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回調,但仍然有同樣的問題。

我還應該做些什麼來解決這個問題?我在這裏錯過了什麼?

+0

update_event_bucket_participants在哪裏定義? – davidwessman

+0

桶模型。 – Raji

回答

0

不是100%肯定這是否會工作,但如果你改變:

Bucket似乎UsersEvents之間的連接模型,它可以容納許多用戶和許多事件?

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,除非您在那裏保存了大量信息,在這種情況下,您應該更改其餘的建模。

+0

感謝您的回覆davidwessman。是。我們需要保存爲該事件添加的每個用戶的狀態。我的意思是,對於某個特定事件,我們需要保存該存儲桶中每個用戶的狀態。所以我們創建了中間表** event_participants「 – Raji

相關問題