在视图中显示相同的项目

时间:2012-09-15 21:46:09

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我的模特:

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 

并获得属于类别的正确房屋。但是我怎样才能在控制器/模型逻辑中做到这一点?

1 个答案:

答案 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

编辑回答,没看到你的众议院有很多类别