I am trying to get my posts tagged with a certain tag to render. My code in the view is
Views/posts/sports.html.erb
<% my_posts = post.find_by_tag("sports") %>
<%= my_posts.each do |post| %>
<%= post.title %><br />
<%= post.body %><br />
<% end %>
my controller for this looks like
def sports
@posts = Post.paginate(:page => params[:page], :per_page => 10)
@post = Post.find(params[:id])
@title = "Newest"
respond_to do |format|
format.html
format.json { render :json => @users }
end
end
I know I have to define the @post variable but I’m not sure what to define it as.
UPDATE
The problem I’m having is a “Couldn’t find Post without an ID” error
Second UPDATE
def find_by_tag name
Tag.find_by_name(name).posts
end
Part of the problem, based on what is shown here, is that you are defining instance variables with Post object(s) in the controller, and then not using them for anything in the view. To retrieve a collection of all the posts tagged “sports,” you’d do the following in the controller:
and in the view:
To add pagination, you can just chain that method to the original:
This is different from your snippet, where you define a
@postsvariable that returns a collection of 10Postobjects, and@postwhich simply finds a post object based on the id passed by the submitting form params. My guess is that this controller action is not getting created by a form submission, so no params are passed, and thereforeparams[:id]is nil, hence the error messages you see. In any event, unless you need either of those items in your view (and there’s nothing here to suggest they’re being used for anything), there’s no reason to create them.What you do need is a collection of posts tagged “sports”, which is what the call above accomplishes. It looks like you are trying to do that with
post.find_by_tag("sports")in the view. The problem is that you are calling thefind_by_tagmethod onpost, which doesn’t exist.Postexists – that’s the Post class, and probably what you mean to be calling. Just changingposttoPostwould probably get you where you want, but content retrieval and presentation are better separated if you create your objects in the controller and then use the view to simply render their attribute data (per the example above).