1
votes

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

2
What makes an author similar to another one? - Ryan Bigg
similar author in the sense? - vijikumar
The author_ids. Which means finding books with similar author_ids - Uchenna
displaying books with the same author_ids as the selected book - Uchenna

2 Answers

1
votes

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
0
votes

you can do like this way,

for example

suppose your author name is "xyz",

in your model

def similar_authors(name)
  where("author_name = ?", name )
end

and in your controller

book.similar_authors('xyz') # you will get all books that have author_name is 'xyz'

if you want to optimize then you can also make a scope for that