简体   繁体   中英

In Rails how do I display only the value of a hash item within an array?

I'm new to ruby/rails and trying to build a simple Projects / Tags app where Projects and Tags are associated as has_and_belongs_to_many to each other. It's basically a simple list of projects that have tags associated, and those tags in turn can be re-used by multiple projects.

I've been loading tags into projects like this:

my_project = Project.create(:name => "My Project")
my_tag = Tag.create(:content => "My Tag")
my_project.tags << my_tag

All appears well until I try to load the info into my View. I have a list of projects, each with a small table below that lists the associated tags:

<table>
 <% @projects.each do |project| %>
   <table>
     <tr>
       <td width="300"><%= project.name %></td>
       <td width="100"><%= link_to 'Edit project', edit_project_path(project) %></td>
       <td width="100"><%= link_to 'Nuke project', project, :confirm => 'Are you sure?', :method => :delete %></td>
     </tr>
   </table>
   <table>
     <tr>
       <td><%= project.tags %></td>
     </tr>
   </table>
 <% end %>
</table>

The View output I get is:

[1] My Project               Edit Project      Nuke Project
[2] [#<Tag id: 1, content: "My Tag", created_at: "2012-03-27 19:27:26", updated_at: "2012-03-27 19:27:26">, #<Tag id: 2, content: "My Other Tag", created_at: "2012-03-27 19:41:04", updated_at: "2012-03-27 19:41:04">]

In line [2] How do I go about only displaying the values of :content and not the entire hash? Also - is this how I should associate tags with projects?

Would be great if anyone could point me in the right direction. Much appreciated!!

Thanks! Jason

Well project.tags will return an array, so you need to loop over each item and display it. For example try:

project.tags.map {|tag| tag.content}.to_sentence

Map loops through each tag, and we're displaying the content of each tag, finaly outputting it to a sentence.

There are numerous other ways to do that. Have a look at the array methods for more info.

About the other question, has_and_belongs_to_many is fine, but for more flexibility try using has_many :through, as explained here . And here is the reasoning behind that.

如果您使用的是Rails 3.2,则可以使用pluck方法仅提取内容

<%= project.tags.pluck(:content).join(",") %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM