显示来自多个相关表的数据

时间:2011-02-15 17:08:34

标签: ruby-on-rails

使用Rails 2.3.8。我想显示复杂关系中的数据。

这些在我的模特中:

shop.rb

has_many :city_shops

id | name 
3  | Good Cafe

city_shop.rb

belongs_to :city
belongs_to :shop

id | city_id | shop_id | notes
2  |    4    |    3    | Delicious food in Paris

city.rb

belongs_to :article
has_many :city_shops
has_many :shops, :through => :city_shops

id | article_id
4  |    5

article.rb

has_many :shops, :through => :shop_articles
has_many :cities, :dependent => :destroy

id | user_id | name
5  |    6    | Favorite shops in France

user.rb

has_many :articles

id | login
6  | victor

场景是这样的(可能不合逻辑): ID为6的用户创建了许多文章。假设他创建了这篇名为法国最受欢迎的商店的文章。在本文中,有cities。在每个city中,都有city_shops,其中包含来自shop的详细信息notescity_shops

我还有个人shop页面。我希望访问者知道用户留下的注释,注释的位置以及该用户文章的链接。

shop页面中,它应显示为:

用户备注 “胜利者”中的“美味的巴黎美食”,在“链接到法国最喜欢的商店”中分享。

我希望这个问题比以前更清楚。非常感谢你。

2 个答案:

答案 0 :(得分:1)

<% @shop.city_shops.each do |city_shop| %>
   city_shops notes: <%= city_shop.notes %>
   users: <%= city_shop.city.country.user.username %>
   country_id: <%= city_shop.city.country_id %>
<% end %> 

你的模特有点奇怪。

答案 1 :(得分:1)

Notes by users:<br />
<% @shop.city_shops.each do |city_shop| %>
  "<%= city_shop.notes %>" by "<%= city_shop.city.article.user.login%>", shared in <%= link_to city_shop.city.article.name, "#{url}" %><br />
<% end >

您必须在链接中提供网址,并且您还必须将其添加到文章模型中:

belongs_to :user
相关问题