Form_for vs. form_with in Rails 5 with namespace
Asked Answered
S

1

8

I have a namespaced resource in my Rails 5 app and want the correct form for it.

My scaffold for Platform in Rails 5 gave me:

<%= form_with(model: platform, local: true ) do |form| %> 

In Rails 4 I would include my namespace ('customer') like:

<%= form_for [:customer, @platform] do |f| %>

So what is the equivalent in Rails 5?

Seldan answered 10/1, 2018 at 22:38 Comment(0)
S
16

In your form you would do something like this.

<%= form_for [@customer, @platform] do |form| %>
    ...
<% end %>

In new.html.erb or equivilent new method:

<%= render 'form', customer: @customer %>

In your new controller method (depending on your relationships)

def new
  @customer = @platform.customers.build
end

Using form_with

<%= form_with(model: [:customer, @platform]) do |form| %>
  ...
<% end %>

http://api.rubyonrails.org/v5.1/classes/ActionView/Helpers/FormHelper.html#method-i-form_with

Strachey answered 10/1, 2018 at 22:53 Comment(3)
Is there an option in Rails 5 to achieve this with form_with instead of form_for?Seldan
Yes, the end of the answer shows the form_with version - you include the namespacing in what you pass to the model, like so: model: [:customer, @platform]Patentor
correct me if im wrong but most of your examples are showing nested resources, not namespaced resources.Fiddlefaddle

© 2022 - 2024 — McMap. All rights reserved.