2011-08-13 54 views
5

Foo has_many Bar。我想要做的事,如:在ActiveRecord關係中定義自定義查找器方法?

foo_instance.bars.find_with_custom_stuff(baz) 

如何定義find_with_custom_stuff以便它可在bars關係? (而不僅僅是Bar類的方法?)

更新

我想要做的事比範圍更加複雜。是這樣的:

def find_with_custom_stuff(thing) 
    if relation.find_by_pineapple(thing) 
    relation.find_by_pineapple(thing).monkey 
    else 
    :banana 
    end 
end 
+1

範圍將是可用在這裏。 – rubish

+0

我想添加的東西比範圍要複雜得多。 –

+0

你可以在範圍內做很多複雜的事情,你能詳細說明一下嗎? – numbers1311407

回答

5

範圍,scope在軌道3和named_scope在軌道2

class Bar 
    scope :custom_find, lambda {|baz| where(:whatever => baz) } 
end 

foo_instance.bars.custom_find(baz) 

scope應該返回一個範圍,所以給你的更新,你可能不希望在這裏使用scope。你可以寫,雖然一個類的方法,並使用scoped來訪問當前的範圍,如:在酒吧

class Bar 
    def self.custom_find(thing) 
    if bar = scoped.find_by_pineapple(thing) 
     bar.monkey 
    else 
     :banana 
    end 
    end 
end 
+0

伊斯蘭會議組織。好吧,它的範圍。 –

+0

@John Bachir:你可能不想創建一個方法來查找記錄並從中返回一個屬性,因爲它會打破期望。如果你使用了一些現實的例子,這將更容易理解。考慮'Post.find_tag('john')';那又回來了,發生了什麼?你會期望它真的是'Post.find_by_author_name('john')。tags.first || 「untagged''? – coreyward

+0

我想所有的猴子生意,可以這麼說,可能只是爲了說明這一點?例如如果該方法是'first_monkey'或類似的(並且從圖片中刪除了':banana'),我不認爲這會真的打破預期。 (但是,是一種叫做find_by_custom_stuff的方法,可以用菠蘿搜索並返回一個猴子,這可能是推動最小驚喜原則的極限:-P) – numbers1311407

相關問題