I have an app in Rails 3.0.1 . There is a table called Books which has many lists. I have conditional association with lists depending on whether they are good lists or bad lists.
#Book.rb
has_many :lists
has_many :good_lists, :foreign_key => 'book_id', :class_name => "List", :conditions => {:id => List.good_list_ids}
has_many :bad_lists, :foreign_key => 'book_id', :class_name => "List", :conditions => {:id => List.bad_list_ids}
Currently the conditions are cached when the app is started but I want it to be dynamic as the good_list_ids
and bad_list_ids
can change runtime. I want to be able to find books that are associated with both lists by chaining joins. For eg if good_lists_ids = [1,2,3]
and bad_lists_ids = [4,5,6]
. I would like to get books that are associated with at least one good_list_ids
and at least one bad_list_ids
.
Book.joins(:good_lists).joins(:bad_lists)
I know it can be done by applying filters after fetching the records from db. But is there a way to do this only in sql using AREL?