可以忽略.where方法吗?

时间:2014-10-14 20:33:01

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

我有一个显示用户帖子的页面:

user.posts

我想添加功能,仅显示某个类别的用户帖子:

user.posts.where(category_id: category_id_variable)

为了避免代码重复,我想知道是否可以将代码行保留在两个场景之上,即如果我想显示所有用户的帖子,就会忽略.where方法?

2 个答案:

答案 0 :(得分:1)

在您的控制器上执行操作:

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?

答案 1 :(得分:0)

您要找的是unscope。在您的示例代码中,您可以user.posts.where(category_id: category_variable).except(:where)获得与user.posts相同的结果。

有关详细信息,请参阅ActiveRecord query guides