ruby-on-rails - rails : Displaying published post by all and unpublished post of current_user

标签 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 rails-activerecord

我想知道人们将如何执行以下操作:

  • 用户可以查看所有已发布的帖子
  • 用户可以查看他们未发布的帖子

  • 代码:
    # 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/

    相关文章:

    ruby-on-rails - 用户帐户设计和安全

    ruby-on-rails-3 - 如何在范围内引用belongs_to关联?

    ruby-on-rails - 针对当前 URL 的 ROR if 语句

    devise - 无法将第一个用户插入 Rails/devise 用户表

    ruby - 为什么这些路由从 rake 路由中丢失?

    ruby-on-rails - 由于参数无效 (errorno::EINVAL),Rails 服务器未启动

    ruby-on-rails - 安装 charlock_holmes_bundle_icu -v '0.6.9.2' 的问题

    mysql - 使用 MySQL 和 InnoDB 管理 Rails3 中的事务

    ruby-on-rails - 升级到 Rails 4 时批量分配失败

    ruby-on-rails - Ruby on Rails 的社交媒体共享按钮 Gem