Ruby on Rails 3 ã® Ajax ãããã
ä»ããæã¯ããã¾ãããRails3 ã® Ajax å®è£
ã®æ¹æ³ãç´¹ä»ãã¾ãã
Rails3.1 ãã jQuery ãããã©ã«ãã«ãªããAjaxãRails2ã®é ã¨ã¯éãã¹ã¿ã¤ã«ãªãã¾ãããã¾ããå¹¾ã¤ãã®ãã¿ã¼ã³ãé¸ã¹ãããã«ãªãã¾ããã
ããã§ã¯ä¸ã®ç»åã®ããã«ã rails g scaffold todo due:date task:string ã§ä½ã£ãã¢ããªã®show ãindexç»é¢ã«è¡¨ç¤ºãããç°¡å㪠Ajax ã¢ããªã§èª¬æãã¾ãã
1. Rails2 ã«è¿ãããæ¹
Rails2 ã§ã¯ãview ã«javascriptãæ¸ããã« ajax ã¢ããªãæ¸ããããã«ãªã£ã¦ãã¾ããããããã«è¿ãæ¹æ³ã¯ã
- index.html.erb ã® showã¸ã®ãªã³ã¯ã« :remote => trueãæå®ããAjaxç¨ã®è¡¨ç¤ºã¨ãªã¢ div.show_area ãç½®ãã¾ãã
<% @todos.each do |todo| %> .... <td><%= link_to 'Show', todo, :remote => true %></td> ... <% end %> ... <div id="show_area"></div>
- todos_controller.rb ã® show ã¡ã½ããã®è¡¨ç¤ºã« javascriptãªã¯ã¨ã¹ãã«å¯¾å¿ãã format.js ã追å
def show @todo = Todo.find(params[:id]) respond_to do |format| format.html # show.html.erb format.js # show.js.erb format.json { render json: @todo } end end
- show.js.erb ãã³ãã¬ã¼ãã追å ãããã©ã¦ã¶ã¼ã§å®è¡ããã javascript ãæ¸ãã¾ãã
$('#show_area').html("<%= raw(j(render :partial => 'show_body')) %>")
2. jquery_ujs ã®callbackã使ãæ¹æ³
jquery_ujsã§ã¯ãµã¼ãã¼å´ã¨ãã©ã¦ã¶ã¼å´ãæ確ã«åããã¦ãã¦ãjQueryãåãã人ã«ã¯æé©ãã¨æãã¾ãã
- index.html.erb ã® showã¸ã®ãªã³ã¯ã«ã¯ãããå°ããã¾ããªãã追å ããã¾ããããã¯ããµã¼ãã¼ã« javascriptã§ã¯ãªããhtmlãæ»ãã¦ããã¨ããæ示ã§ãã
... <td><%= link_to 'Show', todo, :remote => true, "data-type" => "html", :class => 'show' %></td> ...
- todos_controller.rb ã® show ã¡ã½ããã¯ãJavascriptããã®ãªã¯ã¨ã¹ãæã«ã¯layoutã使ããªãããã«ããã ãã§ãã
def show @todo = Todo.find(params[:id]) respond_to do |format| format.html { render layout: (request.headers["X-Requested-With"] != 'XMLHttpRequest') } format.json { render json: @todo } end end
- æå¾ã«ãµã¼ãã¼ããéããã¦æ¥ãhtmlãdivã«å ¥ããJavascriptãindex.html.erb ã«è¿½å ãã¾ããjquery_ujsã§ã¯ãµã¼ãã¼ãããã¼ã¿ãåãåã£ãæã« ajax:success ã¤ãã³ããçºçãã¾ãã®ã§ããããåãåããªã¹ãã¼ãæ¸ãã¦ããã¾ãã注æç¹ã¨ãã¦ã¯ ãªã¹ãã¼ã®å¼æ° status ã« ãµã¼ãã¼ããã®htmlãå ¥ãç¹ã§ãã data ã§ã¯ããã¾ããï¼
<div id="show_area"></div> <%= javascript_tag do %> $('a.show').on('ajax:success', function (data, status, xhr) { $('#show_area').html(status); }) <% end %>
3. jQuery ã®ã¿
jQueryã¯ã¨ã¦ãå¼·åã§ããã¤ç°¡æ½ã«è¨è¿°ã§ããJavascriptã©ã¤ãã©ãªã¼ã§ãã:remote => true ã使ããªãã¦ã jQuery ã ãã§ã Ajaxã¢ããªã¯æ¸ãã¾ãã
- index.html.erb ã® Showãªã³ã¯ãã¯ãªãã¯ããæã«ãjQueryã® .getã¡ã½ããã§ãµã¼ãã¼ã«ãªã¯ã¨ã¹ããéããåãåã£ãçµæã div ã«æ¸ãè¾¼ãã°è¯ãã®ã§ãã
- 以ä¸ã®ãããªç°¡åãªã³ã¼ãã§ãã ã¡ãªã¿ã«ããµã¼ãã¼å´ã¯ã2. ã¨åãã§ãã
<% @todos.each do |todo| %> .... <td><%= link_to 'Show', "#", "data-id" => todo.id, :class => 'show' %></td> .... <%= javascript_tag do %> $('a.show').click(function() { $.get("<%= todo_path(9999) %>".replace('9999', $(this).data('id')), function(data) { $('#show_area').html(data) } ) }) <% end %>
使ãåã
2. ã®ã¹ã¿ã¤ã«ã Rails3ã®æ¨æºã§ããããï¼
1.ã®ã¹ã¿ã¤ã«ã¯åç´ãªAjaxã«ã¯è¯ãããããã¾ãããè¤é㪠Javascriptã¢ããªã¯æ¸ãã¾ãããããããã¯ã大å¤ãªã®ã§ Rails2ã®ã¢ããªãã¢ããã°ã¬ã¼ãããå ´å以å¤ã«ã¯ãã¾ã使ãããªããã¨æãã¾ãã
ã¾ãã表示ã«Javascript ãå¤ç¨ãããµã¤ãã§ããã°ãjquery_ujs ã«ãã ãããªã 3. ã®ã¹ã¿ã¤ã«ãè¯ãããããã¾ããã
.