我是新手,请耐心等待,我整天都在搜索此内容。抱歉,这是初学者的问题:)
我有一个定义了多态关联的模型:
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
编辑:社交链接的初始表创建迁移
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
为此创建了迁移(编辑:请注意,该表在迁移时已存在)
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
谢谢或帮助!
问题是我试图访问具有多态名称的关联,而不仅仅是使用模型名称。而不是执行staff.social,我应该使用staff.social_link。我对此感到困惑。
对困惑感到抱歉
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句