0

Suppose I have a one-to-many association

in the Author class

has_many :books

in the School class

has_many :books

in the Book class

belongs_to :authors
belongs_to :schools

Now hitting the SchoolsController#some_method, with params[:id] as a get request parameter, I want to retrieve all the authors of books that are in some param[:id] school. So I wrote this that works

@shools = Books.where(school_id: params[:id])
@books ||= []
@books.each do |book|
   @books << book.user
end

but I don't think it is the correct rails way to do that. Could someone help ?

1
  • This question appears to be off-topic because it is about working code that needs refactoring. It should be on Code Review. Commented Mar 21, 2014 at 15:53

2 Answers 2

4

You should use joins method:

@authors = Author.joins(:books).where(books: {school_id: params[:id]})
Sign up to request clarification or add additional context in comments.

Comments

4

There area a few things wrong with your code.

First, the belongs_to params in your Book class should be singular. belongs_to :author and belongs_to :school

In your controller, you never use the @shools variable, I imagine it's supposed to read @books?

Appending to the @books array from within the each loop is a bad idea seeing as you're looping over @books in the first place.

Once you have all that fixed, you can get your authors back like this (as Marek mentioned in his answer):

@authors = Author.joins(:books).where(books: {school_id: params[:id]})

1 Comment

Great addition to my (probably too) short answer. +1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.