ruby-on-railsrails-activerecordruby-on-rails-5rails-admin

ActiveRecord::StatementInvalid PG::UndefinedColumn: ERROR


I am using rails_admin for admin panel. Just change association in Image model

From this

class Image < ApplicationRecord
   belongs_to :user 
   belongs_to :product 
end

to this

class Image < ApplicationRecord
   has_one :user 
   has_one :product 
end

and User model is

class User < ApplicationRecord
   has_many :images,dependent: :destroy
end

Getting this error when I try to edit user from admin panel.From other side it is working fine.

ActiveRecord::StatementInvalid at /user/72/edit

PG::UndefinedColumn: ERROR:  column users.image_id does not exist
LINE 1: SELECT  "users".* FROM "users" WHERE "users"."image_id" = $1...
                                         ^
: SELECT  "users".* FROM "users" WHERE "users"."image_id" = $1 LIMIT $2

Solution

  • Rails has great documentation. The documentation for has_one found here states that "This method should only be used if the other class contains the foreign key" so it is looking for the foreign key of image_id on the user record. You would create this through a migration; please see this stack overflow post for more information on foreign keys and migrations.

    But before you go that far, please consider: