How to get a scope for all database rows in rails

2019-07-02 06:31发布

问题:

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:

You can do Post.scoped i guess in Rails

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