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
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:
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.