0

如果我有这样的父类:

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>)
4

1 回答 1

1

1)您的属性似乎imageable_type是错误的,因为它应该是一个类名,例如'Component'not 'component'。Rails 默认情况下不会这样做,所以我假设您手动篡改了该列,这就是它无法正常工作的原因

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

于 2018-05-02T21:22:58.447 回答