2009-05-28 49 views
1

在我的應用程序中,用戶可以啓動並參與討論。他們還可以標記討論;當他們這樣做時,會創建一個標籤,其中包含標籤的名稱(如果該標籤尚不存在)以及標籤,該標籤記住哪個用戶標記了哪個標籤與哪個標籤進行了標籤創建。困難的named_scope情況

所以討論模型中,我們有這樣的:

has_many :taggings 
has_many :tags, :through => :taggings 

我試圖創建一個簡單的方法來從一個用戶檢索一個討論的所有標籤。理想情況下,named_scopes將被用來審慎地保持事物的美好和乾淨。我認爲它應該看起來像這樣:

tags = @discussion.tags.from_user(@user) 

在Tag類中寫入這個named_scope變得非常困難。它應該是什麼樣子?我需要以某種方式與Taggings表加入嗎?

回答

1

你需要用表格的Tagging加入它不知何故。方法如下:

class Tag < AR::Base 
    named_scope :from_user, lambda { |user| 
    { :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] } 
    } 
end 
0

也許這樣做。不named_scope的解決方案,但:

tags = @discussion.taggings.find_by_user(@user).map(&:tag) 

不知道,如果你需要在這裏使用taggings.find_by_user_id(@user.id)。完成之後,您將剩下一個數組,其中包含由給定用戶進行的討論中的標記。將該數組映射到taggings.tag-model(我猜你的標記模型屬於標記)。

0

我還沒有機會來測試這一點,但我認爲它可能工作:

class Discussion < ActiveRecord::Base 
    has_many :taggings 
    has_many :tags, :through => :taggings 
end 

class Tagging < ActiveRecord::Base 
    belongs_to :discussion 
    belongs_to :tag 
end 

class Tag < ActiveRecord::Base 
    has_many :taggings 
    has_many :discussions, :through => :taggings 

    named_scope :by_user do 
    def named(user) do 
     Tagging.find_by_user_and_discussion(user, discussion).tags 
    end 
    end 
end 

使用方法如下:

tags = @discussion.tags.by_user.named(@user)