Hi, basically I’m trying to list the last 3 items, which I’ve succeeded
in doing in the template, however I would like to move this code to the
layout instead.
In the controller I have this code:
def list
@posts = Post.find(:all)
@rposts = Post.find(:all, :order => "id desc", :limit => 3)
end
So when I use this code in list.rhtml it displays the last 3 items and
links to them:
[code=]<% for post in @rposts %>
<%= link_to post.title, :action => 'show', :permalink =>
post.permalink %>
<% end %>[/code]
However when I try to move that code from list.rhtml and into the layout
just as before the last 3 posts are shown with the correct links however
when I click on one of the posts I receive this error:
[code=] NoMethodError in Blog#show
Showing app/views/layouts/blog.rhtml where line #45 raised:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Extracted source (around line #45):
42:
43:
44:
Recent Posts:
45:
<% for post in @rposts %>
46: - <%= link_to post.title, :action => ‘show’, :permalink
=> post.permalink %>
47: <% end %>
48:
[/code]
Any help as to why this happens and how to fix it?
Thanks for your reply, I used render partial and it works now, however
I’m having to repeat “@rposts = Post.find(:all, :order => “id desc”,
:limit => 3)” under every def ___ in the controller, is there a way to
make it apply to all?
I’ve just started programming in Rails, so my comment may not count
for much, but it seems to me that you’re trying to put a method in the
layout, and layouts, as far as I know, accepts built-in helper
methods. Because it’s not correlated with the folder named off of the
controller you’re using, the layout can’t find the variable @rposts;
layouts doesn’t receive any data from the controller branching off of
Application Controller.
I’d advise you to create a partial instead. Partials are rhtml files
whose name starts with an underscore (for example: ‘_post.rhtml’).
Put that into the controller file, and then bring that up in the
layout via the code line: <%=render(:partial=>“post”)%>
Thank you very much you’ve been great help! Everyone works wonderfully
now.
If it’s in a controller, make a private (actually, leaving it public
is fine, but private gives better security :-)) method that has that
one line:
private
def find_post
@rposts = Post.find(:all, :order => “id desc”, :limit => 3)
end
And then simply add this line right under the class name
before_filter(:find_post)
Now, all methods will call that line first! And if you like, you can
add as many before_filters as you please (before_filter also accepts
the 2nd parameter :only=>[‘method1’, ‘method2’]
or :except=>[‘method1’, ‘method2’], if certain methods doesn’t need
that filter)
Any controllers extending off of this one will also call the
before_filter method, so be careful (I had that problem once).
On Aug 6, 11:55 am, Sasha A. [email protected]