If I have a parent class like so:
class Component < ApplicationRecord
include Imageable
end
And that concern looks like so:
module Imageable
extend ActiveSupport::Concern
included do
has_one :image_attachment, as: :imageable, dependent: :destroy
end
end
And that class looks like this:
class ImageAttachment < ApplicationRecord
belongs_to :imageable, polymorphic: true, optional: true
has_attached_file :data
end
Why can't they find each other given these two instances?
ImageAttachment.last
=> <ImageAttachment id: 12, imageable_type: "component", imageable_id: 3, data_file_name: "tumblr_nb88njd2DF1sfwp0ho1_1280.jpg", data_content_type: "image/jpeg", data_file_size: 63794, data_updated_at: "2018-05-02 11:07:12", created_at: "2018-05-02 10:37:48", updated_at: "2018-05-02 11:07:13">
Component.find(3)
=> <Component id: 3, name: "Testing", body: "Test body", created_at: "2017-11-22 02:43:03", updated_at: "2018-05-01 23:50:01">
Component.find(3).image_attachment
=> nil
ImageAttachment.last.component
=> NoMethodError (undefined method `component' for #<ImageAttachment:0x00007fea291ac1e0>)
1) It seems that your imageable_type
attribute is wrong, because it should be a class name e.g. 'Component'
not 'component'
. Rails would not do this by default, so I assume you tampered with that column manually and that is why it is not working
2) ImageAttachment.last.component
-> this won't work because your association for ImageAttachment is belongs_to :imageable
, so in order to get parent, you need to call ImageAttachment.last.imageable