【发布时间】:2016-03-17 00:12:38
【问题描述】:
我是 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
编辑:社交链接的初始表创建迁移
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
感谢或帮助!
【问题讨论】:
-
你到底有什么问题?
标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations