Ruby on rails 有很多:通过:外键

Ruby on rails 有很多:通过:外键,ruby-on-rails,foreign-keys,has-many-through,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 <

我的模型是这样的:

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
class Post < ActiveRecord::Base
  set_primary_key :guid
  [...]
end
class Post:可共享,:主键=>:guid,:外键=>:可共享的\u guid
有很多:方面,:通过=>:方面
结束
类AspectVisibilitytrue,:主键=>:guid,:外键=>:可共享\U guid
验证是否存在:可共享
结束
类方面:aspect\u可见性,:source=>:shareable,:source\u type=>'Post'
结束
我的问题是,当我将帖子插入一个方面时,帖子的id作为帖子的键插入到AspectVisibility中。但实际上应该插入Post的guid

我见过这样的解决方案:

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
class Post < ActiveRecord::Base
  set_primary_key :guid
  [...]
end
class Post
但我一般不想更改POST的外键,只想更改AspectVisibility关联

有人能告诉我怎么做吗


谢谢

我尝试了同样的方法,文章的guid作为可共享的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=aspect.create(:name=>“name”)
>#
>post=post.create(:guid=>guid',:name=>name)
>#
>aspect.posts[#]
>aspect.aspect\u可视性
>[#]

请注意aspect_可见性中可共享的_guid的值。它被设置为post的guid,而不是id。

如果您为示例中的所有模型发布代码,则会有所帮助