Hi all,
I am trying to achieve what I think will be a fairly complex query using the magic of Rails without having lots of ugly looking SQL in the code.
Since my database is dealing with rather specialised biomedical models I'll translate the following to a more real world scenario.
I have a model Book that
has_many :chapters
and Chapter that
belongs_to :book
Say for instance Chapters have a name attribute and the names can be preface ,introduction and appendix, and a Book could have a Chapter named preface and a Chapter named introduction but no Chapter named appendix. In fact any combination of these
I am looking to find all Books that have both Chapters named preface and introduction.
At present I have a named_scope as follows
Book
named_scope :has_chapter?, lambda { |chapter_names|
condition_string_array = []
chapter_names.size.times{condition_string_array << "chapters.name = ?"}
condition_string = condition_string_array.join(" OR ")
{:joins => [:chapters] , :conditions => [condition_string, * chapter_names]}
}
If I call Book. has_chapter? ["preface", "introduction"] this will find me all books that have either a Chapter named preface or introduction. How could I do a similar thing that would find me isolates that both Chapters preface and introduction?
I am not that familiar with SQL so am not quite sure what kind of join would be needed and whether this could be achieved in a named scope.
Many thanks
Anthony