How to specify controller and action in rails form

Leave a comment

Here’s a simple example of how to create a form specifying the controller action method in the form request.

rails-form

routes.rb

  match '/load',      to: 'load#new',           via: 'get'
  match '/load',      to: 'load#create',        via: 'post'

load/new.html.erb


<%= form_tag({controller: "load", action: "new"}, method: "post") do %>
    <%= label_tag(:q, "Search for:") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Search") %>
<% end %>

load_controller.rb

class LoadController < ApplicationController

  def new

  end

  def create
    raise "foo"
  end

end

Here I am just purposely raising an exception to see if I hit the create method.

Running it looks like this

rails-parameters

You can see and pull the request params at the bottom like this:

  def create
    ...
    query = params[:q]
  end

How to return Json data from MVC controller

5 Comments

// AJAX: Called by the JqGrid control
public ActionResult Grid(JqGridSearchCriteria criteria)
{

 var draftJson = new {
      total = 1,
      page = 1,
      records = 1,
      rows = new[]
      {
       new{
          id = 8,
          cell = new[]
          {
          "data1",
          "data2",
          "9/13/2010",
          }
          }
     },
};

   return Json(draftJson, JsonRequestBehavior.AllowGet);
}

Quick rails controller example

Leave a comment

The simplest way to create a new rails page (with the an action controller) is to use the generate command:

$ script/generate controller Pages home contact

This automatically updates the config/routes.rb table and creates the corresponding controllers and views as follows:

app/controllers/pages_controller.rb
app/views/pages/home.html.erb
app/views/pages/contact.html.erb

Which you can then view and edit at:

http://localhost:3000/pages/home
http://localhost:3000/pages/contact

To add a new page to the same controller (i.e. an about page)

http://localhost:3000/pages/about

you need to do three things:

1. Create an ‘action’ in your controller

app/controllers/pages_controller.rb

class PagesController < ApplicationController
   def home
   end

   def contact
   end

   def about
   end
end

2. Update the route table:

config/routes.rb

SampleApp::Application.routes.draw do
   get "pages/home"
   get "pages/contact"
   get "pages/about"
end

Actually you may not need to do this. For 2.3.5 (my current version) the routes.rb class had:

ActionController::Routing::Routes.draw do |map|
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

which is good enough to automatically route generic views to the appropriate controller and action.

3. Stub out your new ‘view’

app/views/pages/about.html.erb

<h1>Pages#about</h1>
<p>Find me in app/views/pages/about.html.erb</p>

And with that you are done! You should not have a new page ready to be edited at:

http://localhost:3000/pages/about

%d bloggers like this: