Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specific association to acts_as models #10

Open
igrek8 opened this issue Aug 17, 2014 · 0 comments
Open

Specific association to acts_as models #10

igrek8 opened this issue Aug 17, 2014 · 0 comments

Comments

@igrek8
Copy link

igrek8 commented Aug 17, 2014

Please correct me or suggest,

My concern is how to get a specific collection from has_many in Test::Owner models rather than generic?

When specifying

# adding to super_class.rb
belongs_to :ownerable, polymorphic: true

# change in owner.rb
has_many :sub_classes_a, as: :ownerable, class_name: 'Test::SubClassA'

and trying to get specific collection through has_many by invoking owner.sub_classes_a, Rails will automatically include the column test_sub_classes_as.ownerable_id in select query which is only possible in test_super_classes table giving an exception such column not found in table sub_classes_as.

With the following definition

# super_class.rb
class Test::SuperClass < ActiveRecord::Base
  belongs_to :ownerable, polymorphic: true
  actable as: :superclassable
end

# super class migration
create_table :test_super_classes do |t|
  t.references :ownerable, polymorphic: true
  t.actable as: :superclassable
  t.timestamps
end

# sub_class_a.rb
class Test::SubClassA < ActiveRecord::Base
  acts_as :super_class, as: :superclassable, class_name: 'Test::SuperClass'
end

# sub_class_b.rb
class Test::SubClassB < ActiveRecord::Base
  acts_as :super_class, as: :superclassable, class_name: 'Test::SuperClass'
end

# owner.rb, has_many actables
class Test::Owner < ActiveRecord::Base
  has_many :sub_classes_a, as: :ownerable, class_name: 'Test::SuperClassA'
end

# special_owner.rb, has_many actables, STI from Test::Owner
class Test::SpecialOwner < Owner
  has_many :sub_classes_b, as: :ownerable, class_name: 'Test::SuperClassB'
end

I am able to do Test::Owner.new(sub_classes_a: [Test::SubClassA.new]).save to save a specific object in the format

// table: test_super_classes (generic)
id: xx
ownerable_id: xx
ownerable_type: Test::Owner
superclassable_id: xx
superclassable_type: Test::SubClassA
...     

However, in my design I have to have has_many with specific class_name: 'Test::SubClassA' to enforce only these objects to be stored and referenced from the model. Moreover, SubClassA and SubClassB have to have a reference back to the owner

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant