Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does <%= f.submit %> know where to post?

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
like image 545
Justin Reyes Avatar asked Sep 19 '15 01:09

Justin Reyes


3 Answers

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

like image 105
Dane O'Connor Avatar answered Oct 26 '22 14:10

Dane O'Connor


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

like image 38
akbarbin Avatar answered Oct 26 '22 15:10

akbarbin


<%= 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

like image 29
Pavling Avatar answered Oct 26 '22 15:10

Pavling