问题描述
我有这个代码将一个表与另一个表相关联。使用Set它会收集所有数据,只有在有其他类似值的情况下才显示一次。
I have this code which associates one table to another. Using Set it collects all data and only shows it once if there are other similar values.
genre_names = Set.new
<% @pm_relationships = PmRelationship.where(:people_id => @person.id) %>
<% @pm_relationships.each do |pm_relationship| %>
<% @movie=Movie.find(pm_relationship.movie_id) %>
<% @mg_relationships = MgRelationship.where(:movie_id => @movie.id) %>
<% @mg_relationships.each do |mg_relationship| %>
<% @genre=Genre.find(mg_relationship.genre_id) %>
<% genre_names.add(@genre.name) %>
<% end %>
<% end%>
# actual view code
<ul class="basic-info-genres">
<%= "<li>#{genre_names.to_a.join('</li><li>')}</li>".html_safe %>
</ul>
我的问题是如何在提供的打印代码中使用link_to
My problem here is how a link_to would work in the print code provided
<%=< a>< li>< button>< span>#{genre_names.to_a.join('< / span>< ; /按钮>< /立GT;< / A>< a取代;<李><按钮><跨度>')}< /跨度>< /按钮>< / li>< / a>。html_safe%>
如何使上述打印链接到 /流派/<%= @ genre.id%GT;
?
How to make the above print to have this link to /genres/<%=@genre.id%>
?
我试过
<%=< a href = /genres/#{@genre.id}'><li><button><span>#{genre_names.to_a.join('</span></按钮>< ; /立GT;< / A>< a取代;<李><按钮><跨度>')}< /跨度>< /按钮>< /立GT;< / A>中。 html_safe%>
但这仅链接到显示的第一个类型
but this only links to the first genre shown
任何想法?
谢谢
推荐答案
添加到流派整个@类型,不仅是@ genre-name,那么你可以在视图代码中使用每个循环。
Add to genres the whole @genres, not only the @genre-name, then you can use the each-loop in the view code.
对于Controller(你应该有你的程序逻辑) :
For the Controller (you should have your programmic logic there):
@genres = Set.new
@pm_relationships = PmRelationship.where(:people_id => @person.id)
@pm_relationships.each do |pm_relationship|
movie=Movie.find(pm_relationship.movie_id)
@mg_relationships = MgRelationship.where(:movie_id => movie.id)
@mg_relationships.each do |mg_relationship| %>
genre=Genre.find(mg_relationship.genre_id) %>
@genres.add(genre) %>
end
end
视图:
<ul class="basic-info-genres">
<% @genres.each do |genre| %>
<li><%= link_to genre.genre_name, "#{root_url}genres/#{genre.id}" %></li>
<% end %>
</ul>
这篇关于Rails link_to .each join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!