While messing on rails I coded this:
<%= form_for :creature, url: "/creatures", method: "post" do |f| %>
<%= f.text_field :name %>
<%= f.text_area :description %>
<%= f.submit "save creature" %>
<% end %>
I clearly understand where this posts. However I found this also works:
<%= form_for @creature do |f| %>
<%= f.text_field :name %>
<%= f.text_area :description %>
<%= f.submit "save creature", class: "btn btn-default"%>
<% end %>
I ran through the folders on my rails app, and I know that it's still posting to this endpoint post '/creatures' => 'creatures#create'. And I want to know how on earth the second block of code knows to still post to that endpoint. Moving from Node.JS to Rails is a bit mind bending.
Here is my controller for the curious:
class CreaturesController < ApplicationController
def index
@creatures = Creature.all
end
def new
@creature = Creature.new
end
def create
new_creature = params.require(:creature).permit(:name, :description)
creature = Creature.create(new_creature)
redirect_to "/creatures/#{creature.id}"
end
def show
id = params[:id]
@creature = Creature.find(id)
end
end
The form_for
helper interprets the model given to it (in this case @creature
) and uses rails conventions to calculate the route. Look at the generated html form.
See the docs here for more info: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
Rails make a form use form builder
so every object or url will generate the url default.
To create a form within this template, you will use a form builder. The primary form builder for Rails is provided by a helper method called form_for. To use this method, add this code into
You can get more information here form builder rails
<%= f.submit %>
doesn't know anything about where or what to POST. That just creates a submit tag in the form.
The important bit is the form_for
helper (you can also use form_tag
for non-resourceful forms). It can create the path for the form action from the resource for you, and has parameters for specifying the method (POST, GET, etc).
http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With