我的模特:
class House < ActiveRecord::Base
has_many :category_join_table
has_many :categories, :through => :category_join_table
end
这些类别是“lux”,“for two for two”等等。
class CategoryJoinTable < ActiveRecord::Base
belongs_to :house
belongs_to :category
end
我的想法是在房产展示页面上显示属于同一类别/类别的其他房屋。我可以在控制台上做到这一点:
a = Category.find(4)
a.houses
并获得属于类别的正确房屋。但是我怎样才能在控制器/模型逻辑中做到这一点?
答案 0 :(得分:1)
我个人在House模型中创建了一个实例方法:
def related_houses
House.joins(:categories).where("categories.id IN (?) AND houses.id != ?", self.categories, self.id)
end
除了现在的房子外,你基本上找到了至少有一个共享类别的所有房屋。
然后在视图中,只需遍历您的房屋实例:
<% @house.related_houses.each do |related_house| %>
<!-- OUTPUT related_house stuff HERE -->
<% end %>
你应该完成:)如果你愿意,也可以为相关的房屋增加一个限制,如果需要,可以从视图中传递给它(默认为5):
def related_houses(limit = 5)
House.joins(:categories).where("categories.id IN (?) AND houses.id != ?", self.categories, self.id).limit(limit)
end
编辑回答,没看到你的众议院有很多类别