Wednesday, June 8, 2011

Rails 3 JQuery Ajax. simple a-z

1. create new Rails project:
    $rails new myapp -d mysql
2. edit file myapp/config/database.yml change username and password fit with your mysql db
    then create db:
    $rake bd:create
3. install jquery.
    #edit myapp/Gemfile add the follow line:

    gem jquery-rails

    #run bundle

    $cd myapp
     $bundle install

    #generate jquery

    $rails g jquery:install

    note: type Y when it ask for replace rails.js

4. edit app/views/layout/application.html.erb

    replace <%= javascript_include_tag :default%> 
    by        <%= javascript_include_tag 'jquery','rails','application'%>

5. create a post function

    $rails g scaffold Post title:string content:text
     $rake db:migrate

    run application to make sure everything ok:

    $rails server

    open browser http://0.0.0.0:3000/posts to check.
    play around to see how it work (create some posts and delete  .etc..)

6. note that when we create a new post it return to posts list page after successful create.
Now we want it will display the content of the new post in current page. we will use Ajax. Jquery  make it easy.

    #edit app/views/posts/_form.html.erb
    change <%= form_for(@post) do |f| %>
    to <%= form_for(@post, :remote => true) do |f| %>

    #edit app/views/posts/new.html.erb
    add <div id="saved_post"></div> this is the place to display the new post when it be created

    #edit app/controllers/posts_controller.rb
    in create method change the the two line format.xml {....} to format.js
    it will return to js.erb file with the name like method name in this case it is create.js.erb

    #create app/views/posts/create.js.erb file with content:
     $('#saved_post').html("<h1>Title:<%= escape_javascript(@post.titel) %></h1>").append("Content:<%= escape_javascript(@post.content) %>");

    this code will display the post was create in current page.
7. Run and see how it work.

No comments:

Post a Comment