如果我有这样的父类:
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>)
答案 0 :(得分:1)
1)您的imageable_type
属性似乎有误,因为它应该是类名,例如'Component'
不是'component'
。默认情况下Rails不会这样做,所以我假设您手动篡改了该列,这就是它无法正常工作的原因
2)ImageAttachment.last.component
- &gt;这不会起作用,因为您的ImageAttachment关联为belongs_to :imageable
,因此为了获得父级,您需要致电ImageAttachment.last.imageable