您绝对应该在您的关联连接表中添加一个新字段:这是存储此关系的正确方法。在那之后你可以做很多事情。
您可以添加一些新的 has_many 关联:
class Product < ActiveRecord::Base
has_many :associations
has_many :users, :through => :associations
has_many :weak_associated_users, :class_name => "User", :through => :associations, :source => :user, :conditions => ["associations.strength = ?", "weak"]
has_many :medium_associated_users, :class_name => "User", :through => :associations, :source => :user, :conditions => ["associations.strength = ?", "medium"]
has_many :strong_associated_users, :class_name => "User", :through => :associations, :source => :user, :conditions => ["associations.strength = ?", "strong"]
end
class User < ActiveRecord::Base
has_many :associations
has_many :products, :through => :associations
has_many :weak_associated_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.strength = ?", "weak"]
has_many :medium_associated_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.strength = ?", "medium"]
has_many :strong_associated_products, :class_name => "Product", :through => :associations, :source => :product, :conditions => ["associations.strength = ?", "strong"]
end
#fields: user_id, product_id, strength
class Association < ActiveRecord::Base
belongs_to :user
belongs_to :product
end
然后做类似(在页面上)的事情
<h2>Strongly association users</h2>
<% @product.strong_associated_users.each do |user| %>
...show user info here
<% end %>
或者,您可以不理会新的 has_many 关联,只需在页面上拆分关联记录:
<% grouped = @product.associations.find(:all, :include => [:user]).group_by(&:strength) %>
<% ["weak", "medium", "strong"].each do |strength| %>
<% if associations = grouped[strength] %>
<h2><%= strength %> associations</h2>#
<% associations.each do |association| %>
<% user = association.user %>
...show user info here
<% end %>
<% end %>
<% end %>