如果我有这样的父类:
class Component < ApplicationRecord
include Imageable
end
这种担忧看起来像这样:
module Imageable
extend ActiveSupport::Concern
included do
has_one :image_attachment, as: :imageable, dependent: :destroy
end
end
该类如下所示:
class ImageAttachment < ApplicationRecord
belongs_to :imageable, polymorphic: true, optional: true
has_attached_file :data
end
鉴于这两种情况,为什么他们找不到对方?
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(似乎你的imageable_type
属性是错误的,因为它应该是一个类名,例如'Component'
不是'component'
.默认情况下,Rails 不会这样做,所以我假设您手动篡改了该列,这就是它不起作用的原因
2(ImageAttachment.last.component
->这不起作用,因为您的ImageAttachment关联是belongs_to :imageable
,所以为了获得父级,您需要调用ImageAttachment.last.imageable