gpt4 book ai didi

ruby-on-rails - has_many :through with :foreign_key

转载 作者:行者123 更新时间:2023-12-04 05:45:25 25 4
gpt4 key购买 nike

我的模型是这样的:

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 关联。

有人能告诉我怎么做吗?

谢谢!

最佳答案

我尝试了同样的事情,帖子的 guid 是作为 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 而不是 id。

关于ruby-on-rails - has_many :through with :foreign_key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7141513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com