I have just completed the introduction guide to RoR: http://guides.rubyonrails.org/getting_started.html. It's a great guide and everything works.
I am trying to extend it a little bit by SHOWING tags in the Post view. (The guide sets it up so that you can add tags while adding a post even though Tag and Post are different models).
This is probably something simple, I just don't know how to do it or find this specific information.
For what it's worth:
<p>
<b>Tags:<开发者_Go百科;/b>
<%=h @post.tags %>
</p>
Shows this:
Tags: [#<Tag id: 2, name: "Awesome", post_id: 2, created_at: "2010-02-23 23:53:42", updated_at: "2010-02-23 23:53:42">]
Do I understand you right that you get the tag data together with the post data but are unhappy with the display?
I would suggest something like this to make it look nicer:
<% @post.tags.each |tag|%>
<%= <span class=tag>tag.name</span> %>
<% end %>
Ideally you would wrap this in a partial
_show_tags.html.erb:
<% show_tags.each |tag|%>
<%= <span class="tag">tag.name</span> %>
<% end %>
and call it with
<%= render :partial => show_tags, :collection => @post.tags %>
Ok, I figured it out myself. Should I answer the question myself or vote to close?
Here's the answer anyway:
Go to the posts controller and in the Show action, add this line in:
@tag = Tag.find(params[:id])
This finds the tag needed. Then in the post show view, add this line in:
<p>
<b>Tags:</b>
<%=h @tag.name %>
</p>
This prints the name of the tag.
精彩评论