has_many: через с: foreign_key - PullRequest
       30

has_many: через с: foreign_key

3 голосов
/ 22 августа 2011

Мои модели выглядят так:

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

Моя проблема в том, что когда я вставляю сообщение в аспект, его идентификатор вставляется в AspectVisibility в качестве ключа сообщения.Но на самом деле руководство Post должно быть вставлено.

Я видел такие решения:

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

Но я не хочу менять внешний ключ постов вообще, но только дляАссоциация AspectVisibility.

Кто-нибудь может сказать мне, как это сделать?

Спасибо!

1 Ответ

0 голосов
/ 24 ноября 2011

Я попробовал то же самое, и руководство поста - это то, что вставляется в видимость аспекта как 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">]

Обратите внимание на значение shareable_guid в aspect_visibility. Устанавливается на guid сообщения, а не на id.

...