2021年1月26日星期二

Rails setter method that updates two other fields?

Background

I have some polymorphic relationships - one in particular assetable where I have a parent-child Asset relationship and the parent has various classes.

I also have a global Tracker model that creates a global id type scheme across my various models which I also use the FriendlyID gem for.

My Goal

Something like this:

parent = Tracker.find_by(tracker: '4Q73XEGK').trackable  Asset.find(1).update(parent_tracker: parent.tracker_id)  

thinking I could do something like this - set the new polymorphic relationship by the tracker_id:

  class Asset < ActiveRecord::Base        def parent_tracker        assetable.tracker_id      end               def parent_tracker=(val)                 a = Tracker.find_by(tracker: val).trackable                  assetable_id = a.id        assetable_type = a.class.name                end     end  

Question?

Am I on the right path here (with tweaks) OR show that I am on the completely wrong path here.

I know that there are before_save filters etc. but the setter approach seems more elegant and clear as I can apply this across many other models.

https://stackoverflow.com/questions/65894825/rails-setter-method-that-updates-two-other-fields January 26, 2021 at 09:43AM

没有评论:

发表评论