Reputation: 4089
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
Upvotes: 1
Views: 139
Reputation: 17647
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
Upvotes: 1
Reputation: 6026
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
Upvotes: 0