model - Rails: How to make a setter method find_or_create within an association? -
i have project model belongs_to company , notary. notary belongs_to company.
in projectmodel have following getter / setter methods:
class project < activerecord::base belongs_to :company belongs_to :notary # getter method notary def notary_name notary.try(:name) end # setter method def notary_name=(name) self.notary = notary.find_or_create_by(name: name) if name.present? end end the setter method checks if notary exists or else creates new record.
the issue if user company inputs existing notary name not create new record.
the syntax should like:
self.notary = current_company.notaries.find_or_create_by(name: name) if name.present?
however current_company not available @ model-level. suggestions how solve this?
Comments
Post a Comment