How to get a scope for all database rows in rails 3?

≡放荡痞女 提交于 2019-12-10 18:16:35

问题


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



来源:https://stackoverflow.com/questions/7333198/how-to-get-a-scope-for-all-database-rows-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!