开发者

Complex ActiveRecord association definition

开发者 https://www.devze.com 2023-01-09 05:58 出处:网络
How would you map the dashed association using ActiveRecord? Is there any ActiveRecord-way of doing it? What I want is to get all unique available promotions fo开发者_JAVA百科r a particular item.

How would you map the dashed association using ActiveRecord? Is there any ActiveRecord-way of doing it? What I want is to get all unique available promotions fo开发者_JAVA百科r a particular item.

Diagram

Here are things I thought but I don't really like:

Using custom finder

class Item < ActiveRecord::Base
  has_many :promotions, :finder_sql => "SELECT..FROM promotions..purchase_option_id IN (...)"
end

The dirty and inefficient but rubyish way

my_item.purchase_options.map(&:promotion).uniq

Breaking the PurchaseOption<->Promotion HABTM association and creating a new one for Item<->PromotedPurchaseOption

class Item < ActiveRecord::Base
  has_many :promoted_purchase_options
  has_many :promotions, :through => :promoted_purchase_options
end

Other thoughts

I don't think it's a good idea to use named scopes or defining new methods This won't simply work or will execute inefficient queries if using them:

Item.first.promotions.count
Item.first.promotions.available
Promotion.first.items.all


Maybe this one:

class Item < ActiveRecord::Base
  has_many :purchase_options
  has_many :promotions, :through => :purchase_options, :uniq => true
end


I don't know why you're opposed to named scopes or custom methods. These things can help reduce complexity by encapsulating a lot of the query logic. Whenever possible avoid custom finder_sql on your relationships.

If you're using a deprecated has_and_belongs_to_many relationship method, you should probably switch it to a straight join model. The has_many ..., :through approach will give you a lot more control over the links between models, and you can alter the properties of the join model directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消