I am new to rails so excuse any easy questions. I have developed a blog and I am doing some customization. Just curious, if I want to render a specific post on my index.html.erb page is that possible. For instance if I create a post, title: Cool Post and it has a post_id of 25 in the table, in my index page can I call that specific post to be rendered?
Its hard to say exactly how your system is setup, but the "correct" way to do it in Rails, is to do something like in the Controller
for your page:
def index
@post = Post.find(25)
... Your other code here ...
end
And in your index.html.erb
you could output the post:
<h2><%= h(@post.title) %></h2>
<%= h(@post.body) %>
Of course I am completely guessing on the fields on your @post
Edit: If all you want to do is render the @post
you will still will want to retrieve the post to render in the controller, but then you will want to use a partial and render it from the index.html.erb
file:
Hypothetically, create a
_post.html.erb
file in yourapp/views/posts/
directory, and place whatever rendering code you want there (or abstract it from the existingapp/views/posts/index.html.erb
file. _Note: refer to the post in the partial using a local variablepost
not@post
for greatest flexibility.Then call it in your
index.html.erb
for like this:<%= render :partial => 'posts/post', :object => @post %>
This call assumes the index.html.erb
file is not in the same directory as the _post.html.erb
partial.
I think his question is about rendering/redirecting. You should do (as a last line in your controller)
render @post
or
redirect_to @post
First one to show a post, second one to show post after creation/update.
While dcneiner's solution is technically correct, the Rails way is not to hard code these things. Once the blog is operational you will have to modify the source directly to change this post. This is not advised.
I'm going to suggest you add an extra column to the Posts table to denote whether a Post should be permanently featured on the front page. This allows you to dynamically update your permanent posts with nothing more than a checkmark when you create it.
Eg:
class Post < ActiveRecord
named_scope :featured, :conditions => {:featured => true},
:order => "created_at DESC"
end
Post.featured will return your featured post for use on your front page, ordered newest to oldest.
If you only want one featured post at a time you can add the following to the Post model
before_validation :highlander_clause
def highlander_clause
Post.featured.each{|p| p.update_attribute(:featured, false) if featured
end