我有UserType和User模型。该协会如下;
UserType
has_one :user
User
belongs_to user_type
我试图让用户的user_type名称为X.
我试过了;
User.joins(:user_type).where(:user_type => {name: 'X'}).all
它给出了错误。
`require'
from /app/bin/rails:8:in `<main>'irb(main):015:0> User.joins(:user_type).where(:user_type => {name: 'normal'}).all
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "user_type"
LINE 1: ...sers" ON "user_types"."id" = "users"."user_type_id" WHERE "user_type"."u...
^
: SELECT "users".* FROM "users" INNER JOIN "user_types" ON "user_types"."id" = "users"."user_type_id" WHERE "user_type"."name" = $1
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "user_type"
LINE 1: ...sers" ON "user_types"."id" = "users"."user_type_id" WHERE "user_type"."u...
^
: SELECT "users".* FROM "users" INNER JOIN "user_types" ON "user_types"."id" = "users"."user_type_id" WHERE "user_type"."name" = $1
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "user_type"
LINE 1: ...sers" ON "user_types"."id" = "users"."user_type_id" WHERE "user_type"."u...
答案 0 :(得分:1)
我不确定您的关联设置是否正确
您需要在user_type
User
belongs_to :user_type
您应该在联接查询中使用table name
。
默认情况下,user_type的表名为user_types
User.joins(:user_type).where(:user_types => {name: 'X'}).all
如果你想避免n + 1问题,你应该使用includes
User.includes(:user_type).where(:user_types => {name: 'X'}).all