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)")