2011-08-13 20 views

答えて

31

この場合Rails 3ではArelのmatchesを使用できます。これには、データベースにとらわれないという利点があります。たとえば:

Question.where(Question.arel_table[:content].matches("%#{string}%")) 

これはやや不格好ですが、簡単にスコープに抽出し、例えばに参加することはもちろん:

class Question 

    def self.match_scope_condition(col, query) 
    arel_table[col].matches("%#{query}%") 
    end 

    scope :matching, lambda {|*args| 
    col, opts = args.shift, args.extract_options! 
    op = opts[:operator] || :or 
    where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op) 
    } 

    scope :matching_content, lambda {|*query| 
    matching(:content, *query) 
    } 
end 

Question.matching_content('farming', 'dancing') # farming or dancing 
Question.matching_content('farming', 'dancing', :operator => :and) # farming and dancing 
Question.matching(:other_column, 'farming', 'dancing') # same thing for a different col 

「AND」あなたはスコープを単に連鎖ができます。

編集:+1してみると(後者は試していませんがクールに見えます)両方ともこのタイプの機能を追加します。

+0

非常にクールです、ありがとうございます。私はArelについて読んでいますが、それが何であるかは決して決まっていませんでした。 –

+1

非常に涼しいという意味は+1です。彼に感謝します! – apneadiving

+1

あなたのスコープは地獄のように醜いです。これよりもクラスメソッドとより良い引数リストを使用してください。 モジュールのActiveRecordは モジュールが デフmatch_scope_condition(列、クエリ)を照会: – Hauleth

36

あなたは構文を使用したい:

Question.where("content LIKE ?" , "%#{farming}%") 
+0

質問を展開していただき、ありがとうございます。 –

+4

あなたは次のようなことができます: 'Question.where(" LIKE?AND name is like? "、"%#{search1}% "、"%#{search2}% ")' – Ammar

+0

あなたがそれを書くとき、答えがとても分かります! –

9

あなたが本当にセクシーな条件を必要としている場合、外部依存関係に問題を持っていない、私は非常にMetaWhereをお勧めしますし、それが後継Squeelです:

# MetaWhere 
Question.where(:content.like => '%farming%') 

# MetaWhere with operators overloaded 
Question.where(:content =~ '%farming%') 

# Squeel 
Question.where { :content.matches => '%farming%' } 

# Squeel with operators overloaded 
Question.where { :content =~ '%farming%' } 
+0

ありがとう - Squeelのために非常に役立つ –

+2

を、正しい構文は、 '質問です。ここで{content.matches '%farming%'} ' – rwb

関連する問題