我想知道如何做以下事情:
代码:
# 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
我不确定以什么方式设置有效记录条件以显示我正在追踪的内容。
非常感谢。
答案 0 :(得分: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
现在你有一个正确排序的关系,只有一个范围!
答案 1 :(得分: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