mercredi 9 septembre 2015

belongs_to not making join

I have users table with:

  • id
  • username

and questions table with

  • id
  • asker_id
  • question_text

So when I need to get a question from db I need the username too.

So I made:

class User < ActiveRecord::Base
    has_many :questions
end

class Question < ActiveRecord::Base
    validates :question_text, presence: true
    belongs_to :user, foreign_key: "asker_id"
end

#controller
def index
    @questions = Question.order(id: 'desc')
end

#view
<strong><%= question.user.username %>:</strong>
<%= question.question_text %> at 
<i><%= question.created_at %></i>

I was expectig that questions to make join to users but in console I see:

Question Load (0.2ms) SELECT "questions".* FROM "questions" ORDER BY "questions"."id" DESC User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] CACHE (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]

How do I get a join?

Aucun commentaire:

Enregistrer un commentaire