LoginSignup
1
2

More than 5 years have passed since last update.

rails5でform_forしたものをajax+partialで非同期に表示する

Last updated at Posted at 2018-06-25

やりたいこと

NAVERまとめのようなサービスで、
1つのまとめに情報をajaxでガンガン追加していきたい。

プログラム的には
form_forで送信した情報を保存、
partialを追加する形で非同期描写したい。

概要

partialを用意、HTMLの要素に#novel-cardsを設定。
form_forでnovel#createに情報を送信、
/views/novels/create.js.erb/を実行、
create.jsの中でrenderでpartialを描画し、

novel-cardsにappendToする。

具体的なやり方

html

表示するhtml

app/views/matomes/show.html.haml
#novel-cards
  - @novels.each do |novel|
    = render partial: "novel-card", locals: { novel: novel }

パーシャル(部分テンプレート)

/views/matomes/_novel-card.html.hamlという場所にある。
・[novel]という変数を渡してきて使うようになっている。
・novelはインスタンス変数を渡すことを想定。

app/views/matomes/_novel-card.html.haml
.row
  .card.mx-2.w-100.shadow
    .card-title
      = simple_format(novel.title,:style => "font-size:20px; line-height:160%;")
      = simple_format(novel.description,:style => "font-size:17px; line-height:160%;")
      = simple_format(novel.review,:style => "font-size:20px; line-height:160%;")
    .card-body.pl-2.pt-3.pb-2{:style => "min-height:100px;"}
      .row.pl-3.pb-2.small.text-muted
        = novel.created_at.strftime("%Y/%m/%d/ %H:%M:%S")
      .font-weight-bold.pb-4
        = simple_format(novel.description,:style => "font-size:17px; line-height:160%;")

コントローラ

app/controllers/novels_controller.rb

  def create
    @novel = Novel.new(novel_params)

    respond_to do |format|
      if @novel.save
        format.html { redirect_to @novel, notice: 'Novel was successfully created.' }
        format.json { render :show, status: :created, location: @novel }
        #scaffoldにformat.jsを追加
        format.js
        #format.jsを追加
      else
        format.html { render :new }
        format.json { render json: @novel.errors, status: :unprocessable_entity }
      end
    end
  end

上記コントローラでnovels#createを呼んでいるので、
/views/novels/create.js.erb
を自動で呼んでくれる。
その中でajaxでの自動追加を実装。

コントローラからインスタンス変数@novelを渡して、
renderにて描画、appendToで一番下に追加描画する。

js

app/views/novels/create.js.erb
$("<%= escape_javascript(render partial: '/matomes/novel-card', locals: { novel: @novel }) %>").appendTo("#novel-cards");

//submitの後に、フォームの中身を空にする
$('form').find("textarea, :text, select").val("").end().find(":checked").prop("checked", false);

Rails の form 内で disabled された submit ボタンを再度 enable する

1
2
1

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
1
2