过滤和分类此控制器(Rails)中的帖子的最佳方法



我有一个带有draft列的Post模型。如果用户单击视图中的复选框,则将帖子检查为draft

schema.rb:

create_table "posts", :force => true do |t|
    t.string   "title"
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at",                            :null => false
    t.datetime "updated_at",                            :null => false
    t.integer  "comments_count",     :default => 0,     :null => false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
    t.boolean  "published",          :default => false
    t.datetime "published_at"
    t.boolean  "draft",              :default => false
  end

换句话说,它不被认为是发表的:

POST.RB:

  def publish_post
    unless self.draft == true
     self.published = true
     self.published_at = Time.now
    end
  end

(我不确定有两个列是否彼此相反,这是否是不好的做法,但是它会在"帖子"模型中进行回调,请读取更清晰。请纠正我,如果我错了)。

现在,我想找到一种获取草稿和非选秀权(已发布)帖子的方法。现在,我只知道如何在其发布的日期之前对其进行分类。但是我不知道如何用draft == truepublished == false过滤帖子。

POST_CONTROLLER.RB:

 def index
    @posts = Posts.order('published_at DESC')
  end

这样做的最好方法是什么?

(顺便说一句,我应该使用orderorder_by?有什么区别?)

仅获取不是草稿的帖子:

@posts = Posts.where(:draft => false).order('published_at DESC')

您也可以使用ActivereCord范围来执行此操作,这为您提供了一种更好的方法来查询所有草稿:

class Post < ActiveRecord::Base
   #Create a scope for draft
   scope :draft, where(:draft => true)
end

然后,在您的控制器中 - 您可以找到这样的所有草案帖子:

Post.draft

您可以在此处了解更多信息http://guides.rubyonrails.org/active_record_querying.html#scopes

最新更新