Ruby on Rails Wednesday, September 9, 2015

I'm not sure I'm reading this right, but if you're looking for the answers to the questions asked by a specific user wouldn't it be

@user = User.find(params[:id]
@user.questions = the questions the user asked
@user.questions.answers = the answers to the questions the user asked.

THere's something troubling to me about your model set up but I can't think of what it is.

On Wednesday, September 9, 2015 at 4:18:46 AM UTC-7, Ruby-Forum.com User wrote:
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/c69dcd8a-e802-46db-93b0-64e6a444ae22%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment