Tuesday, February 23, 2010

JQuery on Rails 3.0

Firstly, head over to http://github.com/rails/jquery-ujs and obtain the rails.js file and substitute with the one in our javascript folder.

We will then include the required javascript files,

<%= javascript_include_tag 'jquery','rails','application' %>

Get the jquery.js file from http://code.jquery.com/jquery-1.4.2.js

Now... let's do some trivial testing so that we know JQuery is actually working.


class EntriesController < ApplicationController
respond_to :html, :xml, :js

def index
@entries = Entry.all_entries
respond_with(@entries);
end

def new
@entry = Entry.new
end

def create
@entry = Entry.new(params[:entry])
if @entry.save
respond_with(@entry, :location => entries_path)
end

end

end


We will then create a create.js.erb file which contains the JQuery code that we want to run when then action is invoked.
Let's put something like,
alert("Thanks for visiting!");

The new syntax in Rails 3 is that we will not use remote_form_for no more, but instead

<% form_for @entry, :remote => true do |f| -%>
<%= f.error_messages %>
<%= f.label :title, "Title" %>
<%= f.text_field :title %>


Same is true if it's a link,

<%= link_to 'Ajaxified', :remote => true %>

If done right, the browser should fire an Alert box when the form is submitted.

0 comments:

Post a Comment