【问题标题】:Show equal items in the view在视图中显示相等的项目
【发布时间】:2012-09-15 21:46:09
【问题描述】:

我的模型:

class House < ActiveRecord::Base
    
    has_many :category_join_table
    has_many :categories, :through => :category_join_table

end

类别例如“勒克斯”、“适合两人”等。

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

我的想法是在房屋属性显示页面上显示属于同一类别的其他房屋。我可以在控制台中执行此操作:

a = Category.find(4)
a.houses 

并获得属于该类别的正确房屋。但是如何在控制器/模型逻辑中做到这一点?

【问题讨论】:

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


    【解决方案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
    

    已编辑答案,首先没有看到您的房子有很多类别

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 2018-04-20
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多