has_many:通过:foreign_key

时间:2011-08-21 22:12:43

标签: ruby-on-rails foreign-keys has-many-through

我的模特看起来像这样:

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

我的问题是,当我将Post插入Aspect时,Post的id会作为Post的密钥插入AspectVisibility。但实际上应该插入Post的guid。

我见过这样的解决方案:

class Post < ActiveRecord::Base
  set_primary_key :guid
  [...]
end

但我不想更改Posts的外键,只是为了AspectVisibility协会。

有人能告诉我怎么做吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我尝试了同样的事情,并且对帖子的指导就是将其作为shareable_guid插入到方面可见性中。这就是我在做的事。

>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的值。它被设置为guid of the post而不是id。