LoginSignup
6
6

More than 3 years have passed since last update.

form_withで非同期通信(ajax)

Last updated at Posted at 2019-10-10

https://techracho.bpsinc.jp/hachi8833/2017_05_01/39502
form_withを使用するとき、local: trueをつけないとXMLHTTPRequest通信が行われる。
初期状態がXMLHTTPRequestなので、ajax通信できるやん!!!
ってことで、やってみました。(少し苦労した)

jqueryを使用して実装

routes.rb
resources :posts, only: [:new, :create]
post_controller.rb
class PostsController < ApplicationController
def index;@posts = Post.all;end

def new;@post = Post.new;end

def create
    @post = Post.new(content_params)
    @post.save
end

private
def content_params
    params.require(:post).permit(:content)
end
end
new.html.erb

<%= form_with model: @post do |f|%>
<%= f.text_field :content %>
<%= f.submit "投稿する",id: "submit"%>
<% end %>
<div id="jquery"></div>
create.js.erb
$(function(message) {
        let message_content = (<%= @post.content %>)
        var html = `<div class="action">${message_content}</div>`
        $("#jquery").append(html)
    })

自分が知ってる方法だと、js fileで submitを押したら、rails のrouting => controllerに行って、jbuilder => js fileのdone functionにいく。という手法だったのですが

form_withを使うと、
controllerからaction名に応じた、js.erb fileが呼び出されるという内容になりました。

create.js.erbには、railsのインスタンスの情報が送られていますし、使い方はhtml.erb fileと同じ<%= @post.id %>のような書き方です。

でも、ajaxでhtmlを作成したいという処理はjqueryで書くので上の書き方になりました。

追記:
validationかけた時、

post.rb
validates :content, presence: true

contentが空でも、create.js.erbが呼ばれてしまう。
それを防ぐために
redirect_to root_path if @post.content? == false
をcontrollerに記述してみました。

6
6
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
6
6