hzamani / active_record-acts_as

Simulate multi-table inheritance for activerecord models
MIT License
252 stars 86 forks source link

Child object does not sets the corrent _type on query #75

Closed wbotelhos closed 7 years ago

wbotelhos commented 8 years ago
class Trail < ActiveRecord::Base
  belongs_to :trailable, polymorphic: true
end

class Event < ActiveRecord::Base
  actable

  has_many :trails, as: :trailable, dependent: :destroy

  accepts_nested_attributes_for :trails, allow_destroy: true
end

class Exam < ActiveRecord::Base
  acts_as :event
end

Trail.last.trailable.class.to_s
# "Exam"

Trail.last.trailable.trails.to_sql
# "SELECT \"trails\".* FROM \"trails\" WHERE \"trails\".\"trailable_id\" = 7 AND \"trails\".\"trailable_type\" = 'Event'"

As you can see, if the has_many :trails stay on parent class, it gets the trailable_type as Event, not Exam. There is some way to detect from where the has_many was called to set this type?

I have a has_one that works fine:

class Event < ActiveRecord::Base
  has_one :address, as: :addressable, dependent: :destroy

  accepts_nested_attributes_for :address, allow_destroy: true
end

class Address < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true
end

Address.last.addressable.class.to_s
# "Event"

Address.last.addressable.address

# [2016-04-30T15:45:29] DEBUG ActiveRecord::Base :   Address Load (1.1ms)  SELECT  "addresses".* FROM "addresses"  ORDER BY "addresses"."id" DESC LIMIT 1
#[2016-04-30T15:45:29] DEBUG ActiveRecord::Base :   Event Load (0.4ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = $1 LIMIT 1  [["id", 7]]
#[2016-04-30T15:45:29] DEBUG ActiveRecord::Base :   Address Load (0.4ms)  SELECT  "addresses".* FROM "addresses" WHERE "addresses"."addressable_id" = $1 AND "addresses"."addressable_type" = $2 LIMIT 1  [["addressable_id", 7], ["addressable_type", "Event"]]

Thank you.

manuelmeurer commented 7 years ago

What are the actable and acts_as models in this example?

wbotelhos commented 7 years ago

Hi,

Event is actable and Exame is acts_as :event. I edited the question for a better view. (:

manuelmeurer commented 7 years ago

And what exactly is the problem you run into? AFAICS it's the expected behavior that trailable_type is "event", since it's the Event class that has the association. You can still access the trails of an exam with exam.trails, right? Just yesterday I added a spec for this case since I wanted to make sure it behaves as expected: https://github.com/hzamani/active_record-acts_as/commit/6040ca652aa32f9cf4803956e5be85a8114fed20

wbotelhos commented 7 years ago

I already changed the Trail to a specific ExamTrail. But I guess that is possible exam.trails, but for some reason, that I can't remember, I needed to change. In a future I try again and comment here. Thank you! (: