MrThomas
MrThomas

Reputation: 427

Rails post publishing task

I have a very simple rails 3.0.7 app, and am trying to control when a post is published to general vistors of the site, just by a simple selector form when creating or editing the post.

Whats the best way to approach this task, I'm a bit rusty on my rails, and have no idea how to start!?

Cheers Dan

Upvotes: 1

Views: 130

Answers (1)

Frost
Frost

Reputation: 11957

You can add either a boolean published or a timestamp published_at to the Post model, and then just add that to the create/edit post form.

The boolean method is simple and works if you just want to say whether a post should be published or not, while the timestamp method works if you want to be able to write posts in advance, and then let them be automatically published at some specific date or time.

Then, create a scope to easily retrieve the published posts. This will look a bit different depending on whether you chose the boolean or timestamp method above.

# boolean method
class Post < ActiveRecord::Base
  # ... other stuff
  scope :published, where(:published => true)

  # ...
end

# timestamp method
class Post < ActiveRecord::Base
  # ... other stuff
  scope :published, lambda { where("published > ?", Time.now) }
end

Finally, in your controller where you want to list the published posts to the user, do something like this:

class PostsController < ApplicationController
  def index
    @posts = Post.published
  end
end

Upvotes: 1

Related Questions