I am developing a Rails 4.2.6 API app with a number of polymorphic associations, the problem is touch: true does not show the updated object.
class Post < ActiveRecord::Base
belongs_to :postable, polymorphic: true, touch: true
end
class Event < ActiveRecord::Base
has_many :posts, as: :postable
end
class Agenda < ActiveRecord::Base
belongs_to :event, touch: true
has_many :sessions, through: :days, class_name: 'AgendaSession'
end
class AgendaDay < ActiveRecord::Base
belongs_to :agenda, touch: true
has_many :sessions, class_name: 'AgendaSession'
delegate :event, to: :agenda
end
class AgendaSession < ActiveRecord::Base
belongs_to :agenda_day, touch: true
delegate :event, to: :agenda_day
has_many :posts, as: :postable
end
I am trying to retrieve the Event's attribute 'hashtag' through Post.postable. For the sake of argument lets say I have an event with hashtag: '#rock_events' and a session that belongs to the same event.
@event_post = Event.first.posts.first
@session_post = AgendaSession.first.posts.first
# Through console (and rspec):
@event_post.postable.hashtag
>> '#rock_events'
@session_post.postable.event.hashtag
>> '#rock_events'
# Edit the event's hashtag:
Event.first.update(hashtag: '#pop_event')
>> true
@event_post.postable.hashtag
>> '#rock_events'
@session_post.postable.event.hashtag
>> '#rock_events'
My current dirty fix is:
class Post < ActiveRecord::Base
belongs_to :postable, polymorphic: true, touch: true
belongs_to :event, foreign_key: :postable_id, touch: true
belongs_to :session, class_name: 'AgendaSession', foreign_key: :postable_id, touch: true
end
# and to call a post's parent's hashtag:
@event_post.postable.posts.find(@event_post.id).event.hashtag
@session_post.postable.posts.find(@session_post.id).session.event.hashtag
I understand that I'm reloading all associations in order to get the updated event's hashtag. Anyone knows of a fix or a better work around for this predicament?
Thank You