Ruby on rails 在Rails视图中需要来自多:多连接的数据

Ruby on rails 在Rails视图中需要来自多:多连接的数据,ruby-on-rails,database,has-and-belongs-to-many,Ruby On Rails,Database,Has And Belongs To Many,在大多数情况下,这可能不是最好的解决方案,但我想要一个包含数据表单3表的表 class Media < ActiveRecord::Base belongs_to :user belongs_to :type has_many :ratings end class User < ActiveRecord::Base has_many :medias has_many :rati

在大多数情况下,这可能不是最好的解决方案,但我想要一个包含数据表单3表的表

class Media < ActiveRecord::Base
  belongs_to :user
  belongs_to :type
  has_many :ratings                                           
end

class User < ActiveRecord::Base
  has_many :medias
  has_many :ratings
end

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :media
end
我认为在控制器中使用连接和媒体查找方法会更好,但我不知道具体如何,更可能的解决方案是以媒体和用户为参数的helper方法


您认为什么是最好的解决方案?

这种关联属于您的模型,一种有很多贯穿关系的关系非常适合这种情况

class User < ActiveRecord::Base
  has_many :ratings
  has_many :media, :through => :ratings
end

class Media < ActiveRecord::Base
  has_many :ratings
  has_many :users, :through => ratings
end

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :media
end
然后还可以访问

user.ratings
或:


thanx这帮了我很大的忙,但我没有完全运行它:这就是我目前的情况,问题是当一个用户没有给他评分时,他不在媒体列表中。所以我得到了一个每行不同td计数的表。不,它不起作用。通过media.users,我得到了所有为该电影评分的用户。对于media.users.ratings,我得到了用户给出的所有评分,但不仅仅是该媒体。所以如果我给电影1的用户a评分,给电影2的用户a评分,然后我得到电影1的两个投票,电影2的两个投票。因此,解决方案无效或只是部分解决方案。这是正确的技术。你需要填充关联。K我将其标记为answerd,因为我认为你这样做了。目前,我使用另一个代码来解决“自定义字段”问题,用户可以在其中设置标题和值,这样代码就不再出现在应用程序中。但我从中学到了很多。塔克斯
class User < ActiveRecord::Base
  has_many :ratings
  has_many :media, :through => :ratings
end

class Media < ActiveRecord::Base
  has_many :ratings
  has_many :users, :through => ratings
end

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :media
end
media.name media.comment 
user.ratings
<% media.users.each do |user| %>
  ## Do stuff with user.ratings array
<% end %>
media.ratings.each do |rating|
  rating.your_attribute
  rating.user.your_attribute
end