Home Rails 4: model relationships and indexing for two has_many through models
Reply: 0

Rails 4: model relationships and indexing for two has_many through models

user1231
1#
user1231 Published in June 19, 2018, 6:28 pm

My scenario is as follows

Company has_many purchases as a polymorphic relationship

User has_many purchases as a polymorphic relationship

Note: There is no relationship between users and companies

Purchase belongs_to polymorphism

Purchase has_many items

User has_many items through purchases

Code wise

class User
  has_many :purchases, as: :purchasable, dependent: :destroy 
  has_many :items, through: :purchases
end

class Purchase
  belongs_to :purchasable, polymorphic: true
  has_many :items, dependent: :destroy
end

class Item
  belongs_to :purchase
end

Question 1: What is the appropriate indexing for User.first.items ?

Question 2: I want to find the most recently purchased items grouping them by the item category. What is the most efficient indexing/arel/sql for this? Current, and I'm sure inefficient, code for this is as follows

class User  
  def most_recent_items
    item_ids = Item.select("MAX(id) AS id").group(:category, :puchase_id).collect(&:id) & items.collect(&:id)
    Item.order("created_at DESC").where(:id => item_ids)
  end
end
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324168 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO