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
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/62144f439ea6a2aec9f119a4d112b51c%40ruby-forum.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment