0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsで「rails-ujs」を使った非同期通信

Posted at

実装イメージ

タイトルなし.gif

「こんにちは」ボタンを押すと「上のボタンを押すとメッセージが変わるよ!」のところが「こんにちは」に
「こんばんは」を押すと「こんばんは」にページ遷移せず変わります。

さくっとコード

装飾のコードは抜いています。

config/routes.rb
Rails.application.routes.draw do
  get '/example', to: 'example#index'
  post '/example/greet', to: 'example#greet'
end
app/controllers/example_controller.rb
class ExampleController < ApplicationController
  layout "application"

  def index
    @message = "上のボタンを押すとメッセージが変わるよ!"
  end

  def greet
    @message= params[:greet]
  end
end

上記のlayoutはrails-ujsを使えるやつで
最近のrailsだとデフォルトで使えるはず。。。知らんけど。。。。。

app/views/example/index.html.slim
h1 rails-ujs使用例

/ link_toで実装
= link_to example_greet_path(greet: "こんにちは"), method: :post, remote: true do
  p こんにちは

/ form_withで実装
= form_with url: example_greet_path, remote: true do
  = hidden_field_tag :greet, "こんばんは"
  = submit_tag "こんばんは"

#js-greet
  = render partial: "greet"
app/views/example/_greet.html.slim
p = @message
app/views/example/greet.js.erb
document.querySelector("#js-greet").innerHTML = "<%= j(render partial: "greet") %>"

解説

厳密さにかけているかもです、なんとなく察してください:blush:
formやlinkにremote: trueをつけると非同期でcontrollerのgreetメソッドを経由しgreet.js.erbが実行されます。
このサンプルのgreetメソッドはparamsを変数に入れているだけですが、
modelを操作して結果を返すのが主になると思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?