的has_many:通过与:foreign_key
问题描述:
我的模式是这样的:的has_many:通过与:foreign_key
class Post < ActiveRecord::Base
has_many :aspect_visibilities, :as => :shareable, :primary_key => :guid, :foreign_key => :shareable_guid
has_many :aspects, :through => :aspect_visibilities
end
class AspectVisibility < ActiveRecord::Base
belongs_to :aspect
validates_presence_of :aspect
belongs_to :shareable, :polymorphic => true, :primary_key => :guid, :foreign_key => :shareable_guid
validates_presence_of :shareable
end
class Aspect < ActiveRecord::Base
has_many :aspect_visibilities
has_many :posts, :through => :aspect_visibilities, :source => :shareable, :source_type => 'Post'
end
我的问题是,当我插入后成看点帖子的ID插入AspectVisibility作为邮政的关键。但实际上应该插入邮政的指导。
我见过的解决方案是这样的:
class Post < ActiveRecord::Base
set_primary_key :guid
[...]
end
但我并不想改变文章的外键一般,但只是为AspectVisibility关联。
有谁能告诉我该怎么做?
谢谢!
答
我尝试了同样的事情,并且这篇文章的guid是通过shareable_guid插入到aspect visibility中的。这就是我正在做的。
>aspect = Aspect.create(:name => "name")
>#<Aspect id: 1, name: "name", created_at: "2011-11-24 18:08:53", updated_at: "2011-11- 24 18:08:53">
> post = Post.create(:guid => 'guid', :name => "name")
>#<Post id: 1, guid: "guid", name: "name", created_at: "2011-11-24 18:09:26", updated_at: "2011-11-24 18:09:26">
> aspect.posts << post
>[#<Post id: 1, guid: "guid", name: "name", created_at: "2011-11-24 18:09:26", updated_at: "2011-11-24 18:09:26">]
>aspect.aspect_visibilities
>[#<AspectVisibility id: 1, guid: nil, shareable_type: "Post", **shareable_guid: "guid"**, aspect_id: 1, created_at: "2011-11-24 18:09:48", updated_at: "2011-11-24 18:09:48">]
请注意aspect_visibility中shareable_guid的值。它被设置为引导而不是id。
如果你在你的例子中发布所有模型的代码,它会有所帮助 – Tilo