3

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!

manuels
  • 1,511
  • 3
  • 14
  • 26

1 Answers1

0

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.

>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">]

Note the value of the shareable_guid in the aspect_visibility. It is set to guid of the post and not the id.

vimsha
  • 67
  • 4