2011-11-08 160 views
1

有沒有辦法將查詢方法附加到ActiveRecord :: Relation?ActiveRecord關係:追加查詢方法

例如,我正在搜索用戶,但我只是在某些條件下包含在搜索中的姓氏。你可以將查詢追加到ActiveRecord :: Relation對象嗎?

i_want_to_search_for_last_names = true 
pending_relation = User.where(:first_name => "John") 
pending_relation << where(:last_name => "Doe") if i_want_to_search_for_last_names 
@users = pending_relation.all 

回答

3

你的代碼幾乎是正確的,除了一些事情。在這裏你可以做什麼(不要忘記:你ActiveRelation交易):

i_want_to_search_for_last_names = true 
@users = User.where(:first_name => "John") 
@users = @users.where(:last_name => "Doe") if i_want_to_search_for_last_names 

至於我 - 我在我的項目中使用這種技術。希望它可以幫助你。

+0

工作!這是一個多行的User.where(:first_name =>「John」)。where(:last_name =>「Doe」)'。你的方法應該發生在我身上:)謝謝你的大腦顛簸。 – dhulihan

+0

不客氣,我總是很樂意幫助:) – bor1s