Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 218
t s Avatar asked Feb 01 '17 12:02

t s


1 Answers

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:

  • Why would you change the Image relation from belongs_to :user to has_one :user in the first place? To boil down SQL associations and how Rails maps to them, if user has_many :images then images must necessarily belong_to user; they are opposite sides of the relation, with an exception being a has_and_belongs_to_many relation. If A belongs to B, then B has one (or many) of A. I would strongly encourage you to keep the images as having belongs_to relationships, while User and Product can have_many images. To anecdotally explain why this makes sense: a user might have profile pictures of their face, their house, etc. (has_many :images). A product (shoes) might have multiple pictures of the same shoe (has_many :images), but it is very unlikely that a particular picture of a shoe would map to both a user and a product.
  • I would strongly encourage you manage images and attachments using a gem like attachinary or paperclip. If you're handling uploaded file attachments, libraries like this will save you headaches down the road when it comes to resizing, image compression, etc. I am sure your direction in trying to change the relation was informed by some of the issues that these gems will solve for you.
like image 66
quetzaluz Avatar answered Nov 17 '22 13:11

quetzaluz