Forum: Ruby on Rails DB Code Optimization

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Da34c85670c6f7ee2256ae2cf7a0d7f8?d=identicon&s=25 Sebastian V. (sebastianvirlan)
on 2015-09-09 13:17
Hi, I have the following tables:

- users
-- id
-- username

- questions
-- id
-- asker_id
-- question_text

- answers
-- id
-- answerer_id
-- answer_text

And I wanna make a query to get all questions, with the username who
asked, and all question answers. I made the code but please tell me if
is a good practice:

 class User < ActiveRecord::Base
    has_many :questions
class Question < ActiveRecord::Base
    validates :question_text, presence: true
    belongs_to :user, foreign_key: "asker_id"
    has_many :answers

class Answer < ActiveRecord::Base
    belongs_to :question
    belongs_to :user, foreign_key: "answerer_id"
@questions = Question.joins(:user).joins('LEFT JOIN answers on
answers.question_id =').order(id: 'desc').group(:id)
A user can:

Have more questions

A question can:

Have more answers
This topic is locked and can not be replied to.