我想知道人们将如何执行以下操作:
代码:
# 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
我不确定设置事件记录条件以显示我所追求的内容的正确方法是什么。
非常感谢。
最佳答案
你很接近!只需将 && 替换为 +
# 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
现在您有一个正确排序的关系,并且只有一个作用域!
关于ruby-on-rails - Rails : Displaying published post by all and unpublished post of current_user,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16788273/