Search code examples
ruby-on-railsactiverecordruby-on-rails-3.1ruby-on-rails-3.2

basic active record query


I have a rails app with a three models called author, books and authorships. a book has many authors through a joint model called authorship and author has many books through a joint model called authorships for example

class Author < ActiveRecord::Base
  attr_accessible :name
  has_many :authorships
  has_many :books, :through => :authorships
end

class Book < ActiveRecord::Base
  attr_accessible :name, :author_ids
  has_many :authorships
  has_many :authors, :through => :authorships
end

class Authorship < ActiveRecord::Base
  attr_accessible :book_id, :author_id
  belongs_to :book
  belongs_to :author
end

Now my question is, How can i find books that as the similar authors any selected one

for instance, <% book = Book.first %> something like

<% book.similar_authors.each do |book| %>
  #......
<% end %>

What kind of query will i use to define similar_authors


Solution

  • Your relationship seems to define it already. Try this:

    <% book.authors.each do |author| %>
      <% author.books.each do |book| %>
        #......
      <% end %>
    <% end %>
    

    Or, if you want to only have one iterator, and no dupes, maybe something like (this is the same as above):

    <% book.authors.map { |author| author.books }.flatten.uniq.sort.each do |book|  %>
      #......
    <% end %>
    

    And, to come around full circle, maybe in your model (this is the same as above):

    def books_from_similar_authors
      authors.map { |author| author.books }.flatten.uniq.sort
    end