Andrey Yasinishyn
Andrey Yasinishyn

Reputation: 1861

has_one association isn't working

I have the following ActiveRecord models:

class User < ActiveRecord::Base
  has_one :faculty
end

class Faculty < ActiveRecord::Base
  belongs_to :head, class_name: 'User', foreign_key: :user_id
end

When I try to pull a user using this association with faculty.head I get the record without errors, but when I type user.faculty I get an error:

  Faculty Load (1.8ms)  SELECT "faculties".* FROM "faculties" WHERE "faculties"."user_id" = 1 LIMIT 1
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: character varying = integer
LINE 1: ...".* FROM "faculties"  WHERE "faculties"."user_id" = 1 LIMIT ...

My faculties db schema looks like this:

create_table "faculties", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "user_id"
 end

Is this some PG bug??

Upvotes: 0

Views: 185

Answers (3)

toro2k
toro2k

Reputation: 19230

The error message says:

ERROR:  operator does not exist: character varying = integer

It means that you are trying to compare a varchar value (the user_id field of the faculties table) and an integer value (the id field of the users table), this is not allowed.

You have to define the foreign key user_id as integer:

create_table "faculties", :force => true do |t|
    # ...
    t.integer "user_id"
 end

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

The error occurs because you have your user_id column as a string, not integer.

Upvotes: 2

Salil
Salil

Reputation: 47472

As your user_id is a foreign_key it should be integer

t.string   "user_id"

should be

t.integer   "user_id"

Upvotes: 2

Related Questions