Rails:查询连接表的子项是否存在

时间:2015-09-07 01:14:51

标签: sql ruby-on-rails postgresql activerecord rails-activerecord

设定:

class User < ActiveRecord::Base
  has_many :sales
  has_many :sold_items, through: :sales, source: item
  has_many :returns, through: sold_items
end

class Sale < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
  has_one :return
end

class Item < ActiveRecord::Base
  has_many :sales
  has_many :returned_sales, through: :sales, source: :return
end

class Return < ActiveRecord::Base
  belongs_to :sale
end

问题:

编辑:澄清问题。我希望所有项目都不会由给定用户返回。

提示:商品可能有销售作用于用户:如果商品有两个销售,一个退货,一个不退货,我想要显示该商品。

user_items = user.sold_items.distinct
goal = user_items.reject {|i| i.returned_sales.first}

这不起作用,因为它查询所有的return_sales以查找项目,而不只是查询用户的范围。

编辑:添加返回关联has_one :returned_item, through: :sale, source: :item并查询

returned_items = user.returns.map {|r| r.item}
goal = user_items - returned_items

诀窍但不性感:首选单个查询。

1 个答案:

答案 0 :(得分:0)

关于促销:

Sale.not_returned

然后你可以:

select id,  
       test_id,
       start_date, 
       end_date,
       state,
       case 
         when state = 'FAIL' then lag(start_date) over (partition by test_id order by start_date desc) - end_date
         else null
       end as time_diff
from logs
order by test_id, start_date desc;