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
end
class Question < ActiveRecord::Base
validates :question_text, presence: true
belongs_to :user, foreign_key: “asker_id”
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user, foreign_key: “answerer_id”
end
Controller:
@questions = Question.joins(:user).joins(‘LEFT JOIN answers on
answers.question_id = questions.id’).order(id: ‘desc’).group(:id)
A user can:
Have more questions
A question can:
Have more answers