I have a Post model with a draft column. If the user click on the checkbox in the view, the post is checked as 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
In other words, it is not considered published:
post.rb:
def publish_post
unless self.draft == true
self.published = true
self.published_at = Time.now
end
end
(I’m not sure if it’s a bad practice to have two columns that mean exactly the opposite of each other, but it makes the callback in the ‘Post’ model read clearer. Please, correct me if I’m wrong).
Now I want to find a way of fetching draft and non-draft (published) posts. Right now, I only know how to sort them by their published date. But I don’t know how to filter out the posts with draft == true or published == false.
posts_controller.rb:
def index
@posts = Posts.order('published_at DESC')
end
What’s the best way of doing this?
(By the way, should I use order or order_by? What’s the difference?)
You can also do this with an ActiveRecord scope, which gives you a nicer way to query all draft posts:
Then, in your controller – you can find all the draft posts like this:
You can read more on scopes here
http://guides.rubyonrails.org/active_record_querying.html#scopes