2017-11-09 7 views
0

私のモデルでは2つの異なるスコープを組み合わせたいと思っています。多くのスコープを組み合わせる

Post_model

scope :with_tasks, -> { where(cat: 3).includes(:user).includes(task: :users) } 
scope :with_events, -> { where(cat: 4).includes(:user).includes(event: :users) } 
scope :with_comments, -> {where(comented: true).includes(comments: :user)} 

Post_controller

def index 
    @posts = current_user.posts.with_tasks + current_user.posts.with_events 
end 

しかし、私はそれを達成するために、本当にエレガントな方法はないと思う、と私はコメントスコープを含めることはできません。私はこれ持っています。

このスコープを新しいスコープに結合する方法を知っていますか(下の例のように)?

私の post#indexにこのメソッドを呼び出すことができるようになる何
scope :with_elements, -> { self.with_tasks.merge(self.with_events) } 

@posts = current_user.posts.with_elements 
+0

'current_user.posts.with_tasks.with_events'のように連鎖してみましたか? –

+0

問題はそれは2種類の猫なので、それらをマージする必要があります –

+0

なぜあなたのスコープに 'どこ(cat:3)'を覚えていますか? – max

答えて

0
TASKS = 3 
EVENTS = 4 
scope :with_tasks_and_or_events, ->(cat) { 
    cond = {}.tap do |c| 
    c.merge!(task: :users) if cat.include? TASKS 
    c.merge!(event: :users) if cat.include? EVENTS 
    end 

    where(cat: cat).includes(:user).includes(**cond) 
} 

など、それを使用します。Relational Algebraを使用し、

with_tasks_and_or_events([TASKS]) 
with_tasks_and_or_events([TASKS, EVENTS]) 

または、より良いです。

さらに、データベース構造を改訂してください。

関連する問題