I have an object that uses the ActiveModel::Model concepts:
class TransitProvider
include ActiveModel::Model
# ... more stuff
Underneath the covers, this object is an aggregate for a Provider record and a Service record.
Everything seems to be working very well but the form_with helper doesn't recognize a TransitProvider instance as persisted (because it doesn't have it's own ID) and thus the edit action shows the form with data but submits it as a create instead of an update.
Is there a way to add to an ActiveModel class something so that form_with will treat it as an existing instance instead of a new instance?
Do I need to define something around id or persisted? or something like that?
I can't seem to find anything specific to this use case.
Thanks!
Override
persisted?method. It is defined inActiveModel::API:This method is used by the form builder to decide if it needs to send a post or patch request.
For persisted TransitProvider form does a PATCH request to update.
Otherwise it is a POST to create.
Update what is
persisted?ActiveModel gets its persisted? method from ActiveModel::API it is unrelated to ActiveRecord's persisted? method. Neither take
idattribute into account to decide if the record is persisted:This is important because form builder uses this method to choose between POST and PATCH method and url_for helper uses it to build polymorphic routes.
https://api.rubyonrails.org/classes/ActiveModel/API.html#method-i-persisted-3F
https://api.rubyonrails.org/classes/ActiveModel/Model.html
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resource
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-resolve