has_many :through 和 :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
但我一般不想更改 Posts 的外键,而只是为了 AspectVisibility 关联。
有人能告诉我该怎么做吗?
谢谢!
My models look like this:
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
My problem is that when I insert a Post into an Aspect the id of the Post is inserted into the AspectVisibility as the Post's key. But actually the Post's guid should be inserted.
I have seen solutions like this:
class Post < ActiveRecord::Base
set_primary_key :guid
[...]
end
But I do not want to change the foreign key of Posts in general, but just for the AspectVisibility association.
Can anybody tell me how to do this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我尝试了同样的事情,帖子的 guid 是作为 shareable_guid 插入方面可见性中的内容。这就是我正在做的事情。
请注意aspect_visibility 中shareable_guid 的值。它被设置为帖子的 guid 而不是 id。
I tried the same thing and guid of the post is what getting inserted into the aspect visibility as shareable_guid. This is what i am doing.
Note the value of the shareable_guid in the aspect_visibility. It is set to guid of the post and not the id.