Rodrigo
Rodrigo

Reputation: 4802

ActiveRecord: how to build has_many relation with foreign key or null

I have these two models:

class Promotion < ActiveRecord::Base
  belongs_to :product
end

class Product < ActiveRecord::Base
  has_many :promotions
end

And consider these 3 promotions:

--------------------------
| PROMOTIONS             |
--------------------------
| id | name | product_id | 
| 1  | sale |    NULL    |
| 2  | 10%  |     1      |
| 3  | 20%  |     2      |
--------------------------

When the product_id is NULL, the promotion applies to all products, so I'd like to be able to get all the promotions for a product as follows:

Product.find(1).promotions # => [1,2]
Product.find(2).promotions # => [1,3]

How can I achieve this?

Upvotes: 1

Views: 87

Answers (1)

Joe Kennedy
Joe Kennedy

Reputation: 9443

You could go about finding promotions like this a few different ways. One way would be to just access the Promotion model directly

promotions1 = Promotion.where(product_id: [1, nil])
promotions2 = Promotion.where(product_id: [2, nil])

You could add this as a method in your Product model

class Product < ActiveRecord::Base
  def all_promotions
    Promotion.where(product_id: [self.id, nil])
  end
end

And then use it as follows:

Product.find(1).all_promotions # => [1,2]

Another way could be to concat the promotions of Product object with all promotions that aren't attached to a specific product. This definitely isn't the best solution, since you can't really take advantage of ActiveRecord to order the promotions; you'd have to use array sorting.

def all_promotions
  self.promotions + Promotion.where(product_id: nil)
end

Upvotes: 1

Related Questions