Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form_for vs. form_with in Rails 5 with namespace

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?

like image 889
Oliver Avatar asked Jan 10 '18 22:01

Oliver


People also ask

What is the difference between Form_with and Form_for in rails?

Another difference between form_with compared to form_for and form_tag is that form_for and form_tag generate automatic ids for the input fields. On the other hand, form_with does not. Ids and classes have to be specified. This isn't necessarily considered to be a bad thing.

What is Form_for in Ruby?

This is the name used to generate the input's name (and the params' names), example: = form_for Admin.new, as: :user do |f| #^^^^ = f.input :username # will generate an input like this: <input type='text' name='user[username]' #... /> #

What is form tag in Ruby on Rails?

The form_tag Rails helper generates a form withe the POST method by default, and it automatically renders the HTML that we were writing by hand before. Note: We can explicitly specify what HTTP verb to use for the form_tag if we want something other than POST .


1 Answers

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

like image 79
Trenton Tyler Avatar answered Oct 15 '22 10:10

Trenton Tyler