How to get a scope for all database rows in rails

2019-07-02 06:16发布

assume we the following setup:

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts
end

assume further the user has a boolean attribute 'admin', which indicates if he is a global admin or not.

I want to write a method (or a scope?) for the User class, called 'visible_posts'. If the user is no admin, it should return just its own posts. If he IS admin the method should return all posts in the system.

My first attempt was something like this:

class User < ActiveRecord::Base

  [...]

  def visible_posts
    if admin?
      Post.all
    else 
      posts
    end
  end

end

Problem here is that Post.all returns an Array, but I would rather like to have an ActiveRecord::Relation like I get from posts to work with it later on.

Is it somehow possible to get an ActiveRecord::Relation that represents ALL posts ?

1条回答
甜甜的少女心
2楼-- · 2019-07-02 06:52

You can do Post.scoped i guess in Rails

And later on this you can call .all to fetch the results

查看更多
登录 后发表回答