2012-09-15 59 views
0

我的模型:顯示等項目

class House < ActiveRecord::Base 

    has_many :category_join_table 
    has_many :categories, :through => :category_join_table 

end 

類別是通過例如「勒克斯」,「理想的兩個」 ECT

class CategoryJoinTable < ActiveRecord::Base 
    belongs_to :house 
    belongs_to :category 
end 

我的想法是,以顯示對房產顯示頁面其他房屋至少屬於同一類別/類別。我可以做到這一點我的控制檯:

a = Category.find(4) 
a.houses 

並得到屬於類別正確的房子。但我怎麼能在控制器/模型邏輯中做到這一點?

回答

1

我個人創建房屋模型的實例方法:

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 

編輯答案,沒看到你的房子有很多類別第一

+0

完美!謝謝.... – Remco