Ruby
RubyOnRails

modalによる、model#create,model#new

ハマったこと

結局、slimのシンタックスでハマってることが多い。

前提

$ r g scaffold user name:string

views

app/views/users/index.html.slim

# remote: trueがミソ
= link_to 'New User', new_user_path, remote: true, class: "btn btn-lg btn-primary"
#user-modal.modal.fade aria-hidden="true" role="dialog" tabindex="-1"

app/views/users/new.js.erb


$("#user-modal").html("<%= escape_javascript(render 'form') %>")
$("#user-modal").modal("show")

app/views/users/_form.html.slim


.modal-dialog
  .modal-content
    = form_for @user,remote: true do |f|
      - if @user.errors.any?
        #error_explanation
          h2 = "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
          ul
            - @user.errors.full_messages.each do |message|
              li = message

      .field
        = f.label :name
        = f.text_field :name
      .actions = f.submit

app/views/users/create.js.erb

<% if @status == 'success' %>
    $("tbody").append("<%= j(render("tr", user: @user)) %>");
    $("#user-modal").modal("hide");
<%  elsif @status == 'fail' %>
    alert('error!');
<% end %>

app/views/users/_tr.html.slim

tr
  td = user.name
  td = link_to 'Show', user
  td = link_to 'Edit', edit_user_path(user)
  td = link_to 'Destroy', user, method: :delete, data:{confirm: "Are you sure?"}

controller

def new
    @user = User.new
    ############## 追加(任意) ##############
    respond_to do |format|
        format.html{ redirect_to @user, notice: 'User was successfully created.' }
        format.js {}
    end
    ############## 追加(任意) ##############
end


def create
    @user = User.new(user_params)

    respond_to do |format|
        if @user.save
            format.html { redirect_to @user, notice: 'User was successfully created.' }
            format.json { render :show, status: :created, location: @user }
            ############## 追加 ##############
            format.js { @status = "success"}
            ############## 追加 ############## 
        else
            format.html { render :new }
            format.json { render json: @user.errors, status: :unprocessable_entity }
            ############## 追加 ##############
            format.js { @status = "fail" }
            ############## 追加 ##############
        end
    end
end