Rails 多态关联在模型中不可用

Rails polymorphic association not available in models

我是 rails 的新手,所以请耐心等待,我为此搜索了一整天。如果这是初学者的问题,我们深表歉意:)

我有一个定义了多态关联的模型:

class SocialLink < ActiveRecord::Base
  belongs_to :social, polymorphic: true
end

并且两个模型应该具有此关联之一

class Staff < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :establishment
  has_one :image, as: :imageable
  has_one :social_link, as: :social
end


class Establishment < ActiveRecord::Base
  validates :name, presence: true
  has_one :location
  has_one :social_link, as: :social
  has_many :staff

  accepts_nested_attributes_for :location
  accepts_nested_attributes_for :staff
end

编辑:初始table 社交链接的创建迁移

class CreateSocialLinks < ActiveRecord::Migration
  def change
    create_table :social_links do |t|
      t.string :facebook
      t.string :twitter
      t.string :yelp
      t.string :google_plus
      t.string :youtube
      t.string :instagram
      t.string :linkedin

      t.timestamps null: false
    end
  end
end

此迁移是这样创建的(编辑:请注意 table 在迁移时存在)

class AddSocialLinkReferenceToEstablishmentAndStaff < ActiveRecord::Migration
  def change
    add_reference :social_links, :social_links, polymorphic: true, index: true
  end
end


class UpdateSocialLinkReference < ActiveRecord::Migration
  def change
    remove_reference :social_links, :social_links
    add_reference :social_links, :social, polymorphic: true, index: true
  end
end

编辑:上述迁移后,social_id 和 social_type 可用

#<SocialLink id: nil, facebook: nil, twitter: nil, yelp: nil, google_plus: nil, youtube: nil, instagram: nil, linkedin: nil, created_at: nil, updated_at: nil, social_id: nil, social_type: nil> 

但是,由于某种原因,该关联在这两种型号上都不可用。我无法看到我做错了什么,看起来我已经将它设置为与正在工作的图像模型上的另一个多态关联相同

这个有效

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

谢谢或帮助!

根据 rails guide on polymorphic associations 您的迁移应该看起来更像这样:

class CreateSocialLinks < ActiveRecord::Migration
  def change
    create_table :social_links do |t|
      t.string :name
      t.references :social, polymorphic: true, index: true
      t.timestamps null: false
    end
  end
end

否则table会丢失

问题是我试图访问与多态名称的关联,而不是仅使用模型名称。我应该使用 staff.social_link 而不是 staff.social。我对这部分感到困惑。

抱歉造成混淆