0

Let's say I have a model Listing which has many Tickets, Tickets has status (either on_sale or ordered). Now I want query Listings and if it's tickets has different status, I want too split it into two records.

For instance, there is 1 listing which has 5 tickets, three of them status is on_sale and two of them is ordered, I want get 1 listing which has 3 tickets with its status (Listing also has status) is on_sale and 1 listing has 2 Tickets and the listing's status is ordered.

The point is 1 record split into two based on its association's status.

4

1 回答 1

2

如果我理解你,你需要在内存中表示列表模型,但在数据库中保持不变。

你有 2 个选择,用 Ruby 或 SQL 做。

红宝石

sale_listings = []
ordered_listings = []
Listing.all.each do |l|
  # assign tickets to their appropriate array      
  sale_listings << l if l.tickets.any?{|t| t.status == 'on_sale' }
  ordered_listings << l if l.tickets.any?{|t| t.status == 'ordered' }
end

SQL(通过 Arel)

sale_listings = Listing.joins(:tickets).where("tickets.status = 'on_sale'")
ordered_listings = Listing.joins(:tickets).where("tickets.status = 'ordered'")

这两个示例都未经测试(即在将它们放在这里之前我没有尝试过它们)并且可以进行优化。

于 2013-07-06T20:14:04.510 回答