我是铁杆新手,我卡住了,我有两个型号,
lodge.rb
class Lodge < ActiveRecord::Base
has_many :lodgedetails
accepts_nested_attributes_for :lodgedetails
end
lodgedetail.rb
class Lodgedetail < ActiveRecord::Base
belongs_to :lodge
end
lodge_controller.rb
def show
@lodge = Lodge.all
@lodgedetails = Lodgedetail.all
end
show.html.erb
<% @lodgedetails.each do |l|%>
<tr>
<td><%= l.lodge.name %></td>
<td><%= l.lodge.address %></td>
<td><%= l.lodge.about %></td>
<td><%= l.try(:contact) %></td>
<td><%= l.try(:email) %></td>
<td><%= l.lodge.facility %></td>
<td><span class='glyphicon glyphicon-edit'></span></td>
</tr>
<% end %>
现在当我有2个联系人,2个电子邮件给一个小屋时,它将显示整个行两次。我如何修改它以便它将显示一次记录,如果联系人字段或电子邮件字段有2个值,它应该显示在同一行中,如
name address about contact1,contact2 email1,email2 facility
而不是
name address about contact1 email1 facility
name address about contact2 email2 facility
答案 0 :(得分:0)
这个怎么样:
<% @lodge.each do |l|%>
<tr>
<td><%= l.name %></td>
<td><%= l.address %></td>
<td><%= l.about %></td>
<td>
<% l.lodgedetails.each do |ld| %>
<%= ld.contact %>,
<%= ld.email %>,
<% end %>
</td>
<td><%= l.facility %></td>
<td><span class='glyphicon glyphicon-edit'></span></td>
</tr>
<% end %>
答案 1 :(得分:0)
只需更改迭代方式
<% @lodge.each do |ldge|%>
<tr>
<% ldge.lodgedetails.each do |l|%>
<td><%= l.lodge.name %></td>
<td><%= l.lodge.address %></td>
<td><%= l.lodge.about %></td>
<td><%= l.try(:contact) %></td>
<td><%= l.try(:email) %></td>
<td><%= l.lodge.facility %></td>
<td><span class='glyphicon glyphicon-edit'></span></td>
<% end %>
</tr>
<% end %>
你不需要这样做
@lodgedetails = Lodgedetail.all
Rails方式是
@lodge[0].lodgedetails