Rails:关注未加载 has_one child

Rails: concern doesn't load has_one child

如果我有一个 parent class 像这样:

class Component < ApplicationRecord
  include Imageable
end

这种担忧看起来是这样的:

module Imageable
  extend ActiveSupport::Concern

  included do
    has_one :image_attachment, as: :imageable, dependent: :destroy
  end
end

class 看起来像这样:

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 属性似乎是错误的,因为它应该是 class 名称,例如'Component' 不是 'component'。 Rails 默认情况下不会这样做,所以我假设您手动篡改了该列,这就是它不起作用的原因

2) ImageAttachment.last.component -> 这将不起作用,因为您与 ImageAttachment 的关联是 belongs_to :imageable,因此为了获得父级,您需要调用 ImageAttachment.last.imageable