【发布时间】:2014-09-25 22:10:41
【问题描述】:
我有一个Product 类,它是has_many Gender 到Connection 类实例。我想查询以查找同时具有end_a 和end_b 的产品。当前的类方法有两个注意事项:
- 如果搜索
end_a和end_b相同的位置,则无法正确返回。相反,应该搜索product是否有 2 个实例,而不仅仅是一个对象。 - 当我想要
ActiveRecord_Relation时返回Array。
类方法.query如下,欢迎反馈或意见。
class Product < ActiveRecord::Base
has_many :connections, dependent: :destroy, as: :connectionable
has_many :genders, through: :connections
def self.query(end_a, end_b)
search_base = active.joins(:connections)
end_a_search = search_base.where(connections: { gender_id: end_a } )
end_a_search & search_base.where(connections: { gender_id: end_b } )
end
end
ps:一旦解决这个问题,很可能会将其移至Product 的范围内
【问题讨论】:
-
什么是连接?加入模型?
-
@BroiSatse 修复了上述问题,但
Genders属于Product到Connections -
scope :some_query , ->(end_a, end_b) Product.joins(:connections).where("connections.gender_id = ? OR connections.gender_id = ?", end_a, end_b) -
@bjhaid 我认为这行不通,因为它会返回仅与
end_a或end_b有关系的产品实例。我需要产品与end_a和end_b都有关系。
标签: sql ruby-on-rails ruby activerecord ruby-on-rails-4