How do I generate a form using a model with single table inheritance?

371 Views Asked by At

I have a model Company that has a type field. There are two subclasses Fleet and Dealer.

I know the inheritance is working so I'm now working towards the views working too. However the views/companies/_form.html.erb is producing this error when I click edit on a specific company object on my webpage:

undefined method `dealer_path' for #<ActionView::Base:0x000000000418c0>

Here is the form_with tag:

<%= form_with(model: company, class: "contents") do |form| %>
    *CONTENT*
<%end%>

I want to generate the form based on what company type I am looking at and for all the fields to be populated with their corresponding data.

I found this warning on the ROR site (https://guides.rubyonrails.org/form_helpers.html):

When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify :url, and :scope (the model name) explicitly.

But I do not understand exactly what this means and I believe it is the key to my solution. I wish there was an example of this situation on that guide.

Any help or suggestions are welcome and appreciated!

UPDATE

I changed the form_with tag to be:

<%= form_with(model: [:company @company], class: "contents") do |form| %>

and from my understanding this now generates the URL companies/:id/edit

This is closer, and now brings me to the companies edit page but I can't update now because the changes don't persist.

My NEW question now is, what routes should I have set up? If I'm on localhost:3000/companies and I click 'show company', should this take me to /companies/id: or take me to /dealer/id: / /fleet/id: ?

1

There are 1 best solutions below

0
On BEST ANSWER

I have managed to route the app so it will take me to /companies/id regardless of the type value of the object. This works well and all CRUD is working well now too.

I didn't log exactly what it was I changed this time as I just reverted to a previous commit and rebuilt from there.