4

I wanted to know how one would do the following:

  • A user can view all published Posts
  • A user can view view their unpublished Post

Code:

# Post model
scope :published, where(is_published: true)
scope :unpublished, where(is_published: false)

# Post controller
def index
 @Post = Post.published
 if user_signed_in?
   @Post = Post.published && Post.unpublished.where(user_id: current_user.id)
 end
end

I'm not really sure what the right way to setup an active record condition to display what I'm after.

Any much is much appreciated.

4

2 回答 2

4

你很接近!只需将 && 替换为 +

# Post controller
def index
 @posts = Post.published
 if user_signed_in?
   @posts = Post.published + Post.unpublished.where(user_id: current_user.id)
 end
end

请注意,像这样加入会将 @posts 对象从关系更改为数组。

还请查看@SachinR 的答案,以对该Post.unpublished.where(user_id: current_user.id)行进行很好的改进。

根据您的要求,我认为您可以使用范围做得更好:

#Post model
scope :published_and_user, lambda{|user| where("is_published = ? OR user_id = ?", true, user.id)}
scope :ordered, :order => "created_at DESC"

# Post controller
def index
 @posts = Post.published.ordered
 if user_signed_in?
   @posts = Post.published_and_user(current_user).ordered
 end
end

现在您有了一个正确排序的关系,并且只有一个范围!

于 2013-05-28T09:23:08.600 回答
2

获取所有已发布的记录

   @posts = Post.where("user_id = ?", current_user.id).published

获取所有未发布的记录

   @posts = Post.where("user_id = ?", current_user.id).unpublished

或者

If Post belongs to user 

    class Post
      belongs_to :user
    end

then you can directly use 
current_user.posts.published
current_user.posts.unpublished
于 2013-05-28T09:20:57.663 回答