2016-08-23 6 views
0

フォームパラメータを使用して検索するスコープを作成していますが、スコープを条件と組み合わせる方法や現在のスコープを呼び出す方法がわかりません。別のスコープで複数のスコープを再利用して複数のフィールドをレールに作成する

scope :search, ->(param={}) { 
    all 
    + relation.sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present? 
    + relation.author(param[:author]) if param[:author].present? 
    + relation.assignee(param[:assignee]) if param[:assignee].present? 
    + relation.milestone(param[:milestone]) if param[:milestone].present? 
} 

は、別の例としては、次のようになります:(未テスト)プラス記号を使用して

scope :search, ->(param={}) { 
    relation = all 
    relation = relation.sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present? 
    relation = relation.author(param[:author]) if param[:author].present? 
    relation = relation.assignee(param[:assignee]) if param[:assignee].present? 
    relation = relation.milestone(param[:milestone]) if param[:milestone].present? 
    relation 
} 

答えて

1

ですUser.where(thing: true) + User.where(thing: false)

彼らは両方ともActiveRecord::Relationオブジェクトコレクションを返します。

+0

プラス記号を使用して 'ActiveRecord :: Relation'コレクションを組み合わせることもできますが、これらはすべてオプションなので、ローカル変数を使用する方が意味があります。 :) – codyeatworld

+0

ありがとう、これは私が必要なものです。 :D – KhiemNS

+0

@codyeatworld多分これは愚かな質問ですが、プラス記号は何ですか?あなたは私に例を教えていただけますか? – Aetherus

1

は、ここでは、ローカル変数を使用することができ、私のソースコード

class Issue < ApplicationRecord 

    default_scope { order(created_at: :desc) } 

    scope :state, ->(flag = :open){ 
    where state: flag 
    } 

    scope :sort_by, ->(field = :github_id, sort_type = :asc){ 
    reorder({field.to_sym => (sort_type && sort_type.to_sym) || :asc }) 
    } 

    scope :milestone, ->(milestone){ 
    where milestone: milestone 
    } 

    scope :assignee, ->(assignee){ 
    where assignee: assignee 
    } 

    scope :author, ->(author){ 
    where author: author 
    } 

    scope :search, ->(param={}){ 
    # assign result = default scope here and chain it using below scope 
    sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present? 
    author(param[:author]) if param[:author].present? 
    assignee(param[:assignee]) if param[:assignee].present? 
    milestone(param[:milestone]) if param[:milestone].present? 
    } 

end 
+0

うわー、私はActiveRecordにそのようなクールな機能があるのか​​分からなかった。 – Aetherus

+0

ええ、私もそのことについて学ぶのが好きでした。また、レコードが重複している場合は、 'results.uniq'を使うことができます:) – codyeatworld

+0

ところで、私は' + 'に関するドキュメントを見つけることができません。 – Aetherus

関連する問題