0

I have a Story model that has a :category attribute. Story is also in a HABTM relationship with Tag.

class Tag < ActiveRecord::Base

    has_and_belongs_to_many :stories, :uniq => true

    validates   :name,   :presence => true
    validates   :creator_id,  :presence => true

end

class Story < ActiveRecord::Base

  attr_accessible :title, :category

  belongs_to    :user
  has_and_belongs_to_many :tags, :uniq => true
end

I want to search for stories that either (i) have a category that is in a passed category_array or (ii) have an associated tag.name that is in a passed tag_array.

The first part is straight-forward:

Story.where(:category => category_array)

It's the second part that is stretching my abilities. Any help would be greatly appreciated!

UPDATE

This solves the problem and is pretty easy to read, but is it the best approach? BTW, I had thought of using arel, but I still don't understand how I would use arel across the join table:

Story.includes(:tags).where("tags.name in (tag_array) OR category in (cat_array)")
chuck w
  • 1,741
  • 2
  • 15
  • 34
  • Already answered here http://stackoverflow.com/questions/3291152/ruby-on-rails-3-howto-make-or-condition and here http://stackoverflow.com/questions/3684311/rails-how-to-chain-scope-queries-with-or-instead-of-and – manoj Apr 05 '13 at 17:51
  • Wow, @manoj, those are some contradictory answers (the accepted answer to one of your pointers says arel doesn't support OR, while the most popular answer to the other pointer says that it does). None of the comments to either answer seem to agree on the best way to proceed. BTW, I've found that arel supports OR. But still, I'm not sure how to use arel across a join table. I'm updating my question to give more info. – chuck w Apr 05 '13 at 18:39
  • as the comments in the links say, 'or' is a recent addition to ARel, so the accepted answer was probably written before it was implemented, and the most popular one after. – MrTheWalrus Apr 05 '13 at 19:00
  • The first link says that 'or' is not supported. The question in the second link was written a couple of months later, but the two most popular answers to the question directly contradict one another. One says 'or' is supported and the other says it is not. So, pointing to those questions as providing the answer without explaining the contradiction doesn't help the SO community. – chuck w Apr 05 '13 at 21:51

1 Answers1

0

This solves the problem and is pretty easy to read, but is it the best approach?

Story.includes(:tags).where("tags.name in (tag_array) OR category in (cat_array)")
chuck w
  • 1,741
  • 2
  • 15
  • 34