Syndicate

Feed

Learning Ruby on Rails Day 41

So I modified my Shovell code to use unobtrusive jQuery. It works.

Instead of using the form_remote_tag helper, I am using a regular form_for helper:

<div id="vote-form">
  <% form_for [ @story, Vote.new ] do |f| %>
    <p><%= f.submit 'Shove This' %></p>
  <% end %>
</div>

The following HTML is generated:

<div id="vote-form">
  <form action="/stories/4-hell-breaks-loose/votes" class="new_vote" id="new_vote" method="post">
    <div style="margin:0;padding:0">
      <input name="authenticity_token" type="hidden"
value="qA83IKqd05mqmSl8zyigMzmPeK+o6A+m7b683FhN16U=" />
    </div>
    <p><input id="vote_submit" name="commit" type="submit" value="Shove This" /></p>
  </form>
</div>

Not a trace of JavaScript in it.

Both the jQuery library and application.js are included on the page, so I open application.js and add this JavaScript:

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
jQuery(function() {
  jQuery('#new_vote').submit(function() {
    // $.post(url, data, callback, type)
    jQuery.post(
      jQuery(this).attr('action'),
      jQuery(this).serialize(),
      null,
      'script'
    );
    return false;
  });
});

Ryan Bates' code would have been — if I am to look at the source code provided with his jQuery screencast:

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults 
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
}) 
jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
}; 
$(document).ready(function() {
  $("#new_review").submitWithAjax();
})

I don't need to set my request header to accept “text/javascript”. I ran my app in Safari, IE6, IE7, IE8 and Firefox, and it worked just fine there. Ryan Bates was using jQuery v1.2.6 when he recorded his screencast on Nov 17, 2008 — I'm using jQuery v1.3.2. Maybe that explains it?

Response Headers

I create a create.js.erb template in app/views/votes and in it I place a simple alert with embedded Ruby in it. See what I get:

Screen capture of Shovell

Of course, my votes controller has been set to be able to respond to both a regular POST request and a remote Ajax one:

class VotesController < ApplicationController	
  def create
    @story = Story.find(params[:story_id])
    @story.votes.create
    flash[:notice] = 'Thanks.'
    # The following would work too.
    # unless request.xml_http_request?
      # redirect_to @story
    # end
 
    # Rails uses the HTTP Accept header to determine the request type.
    respond_to do |format|
      format.html { redirect_to @story }
      format.js
    end
  end
 
end

Conjuring a *.js.erb template when you aren't very good at writing jQuery for visual effects

It was easier than I thought. It took me 3 minutes to figure things out. This demo page on the jQuery UI website was useful.

So, to accomplish exactly the same thing that was previously done by my create.js.rjs template:

# replace the content of #id with this HTML
page.replace_html 'vote-score', "Score: #{@story.votes.count}"
# apply visual effect :effet_type to the content of #id
page.visual_effect :highlight, 'vote-score', :duration => 2

I am now using these chained commands on my #vote-score div in create.js.erb:

jQuery('#vote-score').html("Score: <%= @story.votes.count %>").show('highlight', {}, 2000);

I am writing my own JavaScript, jRails is not writing it for me, but it's jQuery so it's mindnumbingly easy.

The JavaScript that was sent to the browser when using jRails was pretty much the same — except it was wrapped in a Try and Catch construct:

JavaScript returned as seen in Firebug

I am so dumb: I should have referred to it when figuring out how to code my effect.

The JavaScript now returned — the one I had to write, that was not generated by Rails — is this one:

JavaScript returned as seen in Firebug

If I feel lazy, I guess I can use RJS.

RJS or ERB

Of course, one can make his jQuery unobtrusive and still use RJS templates. As long as you don't use form_remote_for, form_remote_tag, link_to_remote and periodically_call_remote helpers, but add event handlers to application.js instead, then you're good.

Last edited by Caroline Schnapp about 4 years ago.

Comments

Why start with rails?

Ruby on Rails is awesome and all, but I was a little overwhelmed when I started. I then moved on to just Ruby and converted my Drupal site to Octopress. I may go back to Drupal but only if I want to actually build an application with it rather than just a website.

I don't need to set my

I don't need to set my request header to accept “text/javascript”. I ran my app in Safari, IE6, IE7, IE8 and Firefox, and it worked just http://e-papierossy.com.pl/en/e-papierosy/112-e-papierosy-zerok-zg5421.html fine there. Ryan Bates was using jQuery v1.2.6 when he http://e-papierossy.com.pl/en/e-papierosy/114-e-papierosy-zerok-z5412.html recorded http://e-papierossy.com.pl/en/e-papierosy/116-e-papierosy-zerok-z11334.html
his screencast on Nov 17, 2008 — I'm using jQuery v1.3.2. Maybe that explains it?

Good stuff work

Is many used, the color and the Foundation and its key features, moisturizer, they're inside the process to modify the product with minimal advertising, including some new ones be expected to change.

Javascript

Bei mir kommt aber fehler "Trying to vote on Hell breaks loose". Das verstehe ich nicht.
Aber trotzdem danke für deinen Artikel

I have limited programming

I have limited programming knowledge (an intro course several years ago). I would like to learn Ruby. Can you suggest how best to do it on my own? Good books or websites? nettiarpa

i enjoy your article. great

i enjoy your article. great job. keep it simple

http://www.buyuniquegifts.net/

Many things can cause a problem occurs. Therefore, I always plan and predict the problems that will occur when I do something that does not become a barrier to prolonged. Birthday Gifts are not always about cake and flowers.

Wonderful blog format!

Wonderful blog format! How long have you ever been running a blog for? you make blogging glance easy. The overall glance of your website is great, let alone the content! eatstopeatreviewx

http://twinfountainsec-woodlands.com

Jquery is one of my

Jquery is one of my favorites programming language. it is extremely fast and easy to learn:) Greasemonkey is an another great thing I use this a lot of. Estate planning

These faculty stood together

These faculty stood together with students in solidarity, and they too were beaten and arrested by the police. In writing this letter, I stand together with those faculty and with the students they supported. http://www.thebirthdaysock.com/

Bei mir kommt aber fehler

Bei mir kommt aber fehler "Trying to vote on Hell breaks loose". Das verstehe ich nicht.
Aber trotzdem danke für deinen Artikel Lloret de Mar Spain

works for me too

this totally worked for me too. sea horizon corals at keppel bay ecopolitan

Thump UP!1

Thumbs up guys your doing a truly terrific job!!!

Thomson One | Thomson Two | Thomson Three | Thomson Four | Thomoson Five

woods1 | woods2 | woods3 | woods4

Gla1 | Gla2 | Gla3 | Gla4
Tem1 | Tem2 | Tem3 | Tem4

MEDICINE COURSES FROM NIMS UNIVERSITY JAIPUR

Thanks for sharing nice information with us.i like your post and all you share with us is uptodate and quite informative i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job.

Great!

I personally really appreciate your article. This is a great website. I will make sure that I stop back again.....

Thomson Three @ Bright Hill
Thomson Three @ Bright Hill Dr
Thomson Three @ Bright Hill Drive

works for me!!

Blog gave us useful information to work. You have done an amazing job!.........

The Glades @ Tanah Merah
The Glades @ Tanah Merah
The Glades @ Tanah Merah
The Glades @ Tanah Merah

The Skywoods

This is a nice post in an interesting line of content.Thanks for sharing this article
by The Skywoods Condo
The Skywoods
The Skywoods
The Skywoods @ Dairy Farm
The Skywoods
The Skywoods @ Dairy Farm

Several buses are available

Several buses are available near The Hillford Condo along with shopping centers and restaurants. The Hillford Condo is also near to Bukit Gombak Stadium and Bukit Batok Golf Range.
The Hillford

Jurong West new Condo Launch by MCL And

New Condo in Jurong is a 99-years leasehold Jurong West New Launch Condo development located at Jurong West Street 41. Condo in Jurong

Great Post.. Knowledge is

Great Post.. Knowledge is Power..
Free hold condo at kovan area, visit us now!!
Wait is over..
Tembusu Kovan | Tembusu Wingtai | Tembusu Condo

Living among Lush Greenery, near new hillview mrt
skywoods dairy farm | skywoods condo

Exciting new project at Thomson, near new thomson line MRT
thomson three | bright hill condo | uol brighthill

Luxurious district 10 condominium by renowned developers
mon jervois | jervois condo

3mins walk from buangkok mrt, near shopping malls and amenities
jewel buangkok | jewel cdl | cdl buangkok

alex residences | redhill mrt condo | alexandra view condo

Leider nein

Will bei uns leider auch nicht funktionieren, trotzdem danke

Hj Caroline Schnapp, thanks

Hj Caroline Schnapp, thanks for your sharing, if u free time visit our blog here:

The Rise @ Oxley | Nine residences yishun | The panaroma | Amber skye | The Panaroma | The Hillford | Duo Residences | Hillford condo | marina one residences | D'shire condo | hills twoone | kim tian condo

RoR

Ruby on Rails is state of the art for algorithmic trading. See http://www.algorithmictradingpit.com

Ruby on Rails is state of

Ruby on Rails is state of the art for algorithmic trading.

Ruby on Rails is awesome and

Ruby on Rails is awesome and all, but I was a little overwhelmed when I started. I then moved on to just Ruby and converted my Drupal site to Octopress. I may go back to Drupal but only if I want to actually build an application with it rather than just a website.

I prefer Drupal. RoR quite

I prefer Drupal. RoR quite some steep learning curve.

RIVERBANK @ FERNVALE is a

RIVERBANK @ FERNVALE is a masterful private condominium project scheduled 2017 completion. The 555 unit condo in District 19 at Sengkang West Way and Fernvale Link is planned as an exclusive gated community. Future residents will be able to enjoy peaceful seclusion behind a secure guard house, but will be surrounded with all of the amenities and conveniences imaginable.
http://www.riverbankcondosingapore.com
Riverbank Condominium at Sengkang Fernvale, Singapore

Fantastic!

This is a great work of yours. It's awesome even though I'm new at this but so far, I really like it. Good job!
Active Domain

Great idea!

Fantastic job and a very helpful article even for me. This will absolutely come in handy for me someday. Keep up the great work!

www.megaton.com.sg

High Five!

Such a useful deserves a high five from me! Have been looking for articles like this because I also work with jQuery and other stuff. Thanks!

www.megaton.com.sg

Now I get it

This post has gave me an idea. Now I know what I did wrong with the programming I did in the past. Thanks for this!

www.waikayphotography.com

A job well done!

This is the answer to the same problem tackled in this article. I may not be that good yet when it comes to jQuery, but the instructions here will surely help me with my skills. Cheers!

active-venture.com

Like it!

It's good to know that it took you a very short period of time to figure this out. I, on the other hand, had difficulties why I had problems with this javascript. Oh well, thanks to you, I solved my problem.

www.ihubsolutions.com.my

Problem Solved!

Was looking for something that would look good in my blog. This took me a while to put in my blog but, it really did some improvement. What's even better is that I'm not that confused with this javascript anymore.

www.commonwealthtowers.com

Good to know

This is a good idea of course. I don't know, maybe you're right about what Ryan Bates did but the good thing is, you did it on your own and simplified this common javascript problem.

www.dyslexiakitset.com

Obatt Tradisional Untuk Anak

What is the first word in the phrase "pomupa facav zowa fuwi fihule
obat tradisional untuk anak.
obat tradisional ibu hamil.
obat penurun panas anak.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <css> <html> <javascript> <mysql> <php> <span> <a> <b> <i> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <sup> <sub> <dd> <del> <blockquote> <img> <q> <p> <div>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <javascript>, <mysql>, <php>, <rails>, <ruby>.

More information about formatting options

CAPTCHA
I have to wonder if you're a human spammer or a machine, or less likely someone who cares to leave his or her thoughts behind.