2013-02-19 63 views
0

我正在執行標記系統,並且正在查詢具有範圍的標記對象。將類方法範圍界定爲current_user

例如,我想查找具有特定標記的所有用戶的項目。用類方法我現在可以找到所有對象:

def self.tagged_with(name) 
    Tag.find_by_name(name).items 
end 

但是,這有一個問題。如果我要這樣做:current_user.items.tagged_with(name)這個現有的方法不會返回所有的項目,而不僅僅是current_user擁有的項目嗎?我想這是一個簡單的查詢問題,但我無法弄清楚如何將類方法更改爲集合上調用的某個方法。我嘗試了相反的方式,通過標籤獲取集合,例如... tag.items.where(:user_id => current_user.id),但在這種情況下,這是一種多對多的關係,我一直無法掌握這一點。

限制這樣的查詢的正確方法是什麼?

+0

你能告訴你們的關係了?我是否有權假定你正在使用'acts_as_taggable'? – mathieugagne 2013-02-19 22:38:10

回答

1

在您的User類上創建一個指向Tag類的關聯。

class User < ActiveRecord::Base 
    has_many :tags 
end 

然後,你可以這樣做: current_user.tags.where(...)

如果您還沒有到位的關聯,你需要創建一個遷移有tags表引用您的users表與外國鍵。

0

我認爲這將有助於你:

class Account < ActiveRecord::Base 
     has_many :people do 
      def find_or_create_by_name(name) 
       first_name, last_name = name.split(" ", 2) 
       find_or_create_by_first_name_and_last_name(first_name, last_name) 
      end 
     end 
    end 

    person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson") 
    person.first_name # => "David" 
    person.last_name # => "Heinemeier Hansson" 

所以,基本上可以直接定義你的方法tagged_with進公會!

這個例子是從單證ActiveRecord::Associations