0

I have a page where I user's posts are displayed:

user.posts

I want to add the functionality to only show a user's posts of a certain category:

user.posts.where(category_id: category_id_variable)

To avoid duplication of code I wonder if it's possible to keep the code line above for both scenarios, i.e. somehow ignore the .where method if I want to display all the user's posts?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • 1
    If you only want to do the `user.posts` once, then you could do `user_posts = user.posts` for all cases, then, under the constraining condition, do `user_posts = user_posts.where(category_id: category_id_variable)`. You really can't just ignore the `where`. With Rails lazy loading, `user.posts` is not an expensive statement. – lurker Oct 14 '14 at 20:36
  • 1
    Where is the duplication of code? – PericlesTheo Oct 14 '14 at 20:39
  • @PNY I'm aware now that the question is badly written. This is a (very) simplified query of what I have, and that's why I (visually) would be pleased to save a 3 lines if I don't need to write the query twice. – Fellow Stranger Oct 14 '14 at 20:41
  • 1
    @Numbers I really don't understand where the duplication is. The above perform completely different queries. Do not DRY the above in that context. DRY applies to concepts not lines of code. – PericlesTheo Oct 14 '14 at 20:45
  • You're right. Would like to delete the question, but not possible now that it has answers. – Fellow Stranger Oct 14 '14 at 20:47

2 Answers2

1

On your controller's action:

posts = user.posts 
@posts = posts.where(category_id: category_id_variable).all if category_id_variable.present?
@posts = posts.all unless category_id_variable.present?
SomeDudeSomewhere
  • 3,928
  • 1
  • 23
  • 27
0

What you are looking for is called unscope. In your example code, you would do user.posts.where(category_id: category_variable).except(:where) to get the same results as user.posts.

See ActiveRecord query guides for details.

ptd
  • 3,024
  • 16
  • 29