DEV Community

loading...

Don't name your Rails model Image

mtrolle profile image Morten Trolle ・1 min read

I named my model Image and I'm now realizing that's a bad idea.

I've never used my model with a form previously as it belongs to another model. But now I had to build a form to allow the user to update some of the attributes of my images.

<%= form_with model: image do |f| %>
Enter fullscreen mode Exit fullscreen mode

But suddenly I got errors from the asset pipeline

The asset "[Image" is not present in the asset pipeline.

I even tried providing my form the image path directly:

<%= form_with model: image, url: image_path(image) do |f| %>
Enter fullscreen mode Exit fullscreen mode

But got the exact same error. Okay - so now I realized that the asset pipeline is actually responding to my image_path, even though I created my images routes in config/routes.rb with the usual resources :images syntax.

So long story short. Don't name your model Image. It's always easier to use Rails conversions instead of having to work around them.

Should you do it anyways, then help your self by naming your routes customary. In config/routes.rb you can do it with the as option to your resources statement:

resources :images, as: :img
Enter fullscreen mode Exit fullscreen mode

which gives you the routes helpers:

new_img_path # new
img_path(image) # show
edit_img_path(image) # edit
img_index_path # index - notice it requires index to be specified in method name
Enter fullscreen mode Exit fullscreen mode

and in the form_for you need to tell Rails to use your custom routes:

<%= form_with model: image, url: img_path(image), method: :put do |f| %>
Enter fullscreen mode Exit fullscreen mode

It's not perfect. But when the damage is done it's a lot easier to use custom route names than renaming your model.

Discussion (0)

pic
Editor guide