我无法 respond_to 使用 format.js 。
class UserSessionsController < UserApplicationController
def create
if @counterparty
session[:counterparty_id] = @counterparty.id
@counterparty.update(signed_in: true)
else
flash.now[:error] = 'Invalid email or password'
end
respond_to do |format|
format.js
format.json { render json: @counterparty }
end
end
end
视图/ user_sessions / create.js.erb
alert("Please, notice me!")
服务器日志
Started POST "/user_login" for 127.0.0.1 at 2016-02-19 12:01:43 +0200
Processing by UserSessionsController#create as JS
Parameters: {"utf8"=>"✓", "email"=>"ror@example.com", "password"=>"[FILTERED]", "commit"=>"Sing in"}
Counterparty Load (0.3ms) SELECT `counterparties`.* FROM `counterparties` WHERE `counterparties`.`email` = 'ror@example.com' AND `counterparties`.`password` = 'faa90d7e56eb908c' LIMIT 1
(0.1ms) BEGIN
(0.1ms) COMMIT
Rendered user_sessions/create.js.erb within layouts/user_application (0.0ms)
Rendered shared/_flash.slim (0.1ms)
Completed 200 OK in 634ms (Views: 631.6ms | ActiveRecord: 0.5ms)
这是怎么回事?
现在,关于它的最有趣的部分!
如果我这样,我的警报会显示,但该选项不适合我。
class UserSessionsController < UserApplicationController
respond_to :js, only: :create
def create
if @counterparty
session[:counterparty_id] = @counterparty.id
@counterparty.update(signed_in: true)
else
flash.now[:error] = 'Invalid email or password'
end
respond_with(@counterparty, layout: false)
end
end
application.html.slim
doctype html
html
head
title ActiveAccounting
= javascript_include_tag 'application', 'data-turbolinks-track' => true
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
= csrf_meta_tags
link href="favicon.ico" rel=("shortcut icon") type="image/x-icon" /
body
= render 'shared/flash'
= yield
我该怎么办?
答案 0 :(得分:2)
您的js模板在应用程序布局中呈现。您可以通过以下方式阻止:
format.js { render layout: false }
或通过更全面的解决方案:
class ApplicationController < ActionController::Base
layout proc{|c| c.request.xhr? ? false : "application" }
end