js erb 内的 Rails 会话为空

Rails session inside js erb empty

本文关键字:会话 Rails erb 内的 js      更新时间:2023-09-26

我想在js模板中使用session[:path],但它是空的

我已经定义了session[:path]='my path'然后想像 JS 一样放入

  window.location.href='<%= session[:path]%>';

但返回<%= p session[:path] => nil%>

控制器

    class SessionsController < Devise::SessionsController
  respond_to :js
  layout false
  def create
    self.resource = warden.authenticate(auth_options)
    if resource && resource.active_for_authentication?
      sign_in(resource_name, resource)
    end
  end


  def path
    user = User.find_by(email:params[:email])
    conversation = Conversation.find_by(product_id:params[:product_id],recipient_id:params[:product_owner_id])
      # binding.pry
    p params

    if conversation
      session[:path] = conversation_url(conversation.id)
      p 'conv'
    elsif params[:product_owner_id].to_i == user.id
      session[:path] = request.referer
      p 'back'
    else
      conversation = Conversation.create(sender_id:user.id, recipient_id:params[:product_owner_id],product_id:params[:product_id])
      session[:path] = conversation_url(conversation.id)
      p 'new'
    end
    render json: :ok
  end
end

JavaScript 模板/sessions/create.js.erb

 <% if user_signed_in?%>
  window.location='<%= session[:path] %>';
<% else %>
  $('#login_popup input').parent().addClass('inputbox_error');
  $('#log_error_messages').show();
  $('input').keydown(function(){
    $(this).parent().removeClass('inputbox_error')
    $('#log_error_messages').hide();
  })
<% end %>

你应该在你的path.js.erb文件中有session[:path]

如果你想在你的js文件中使用一些ruby变量(如application.js),我会推荐gon gem

听起来您在app/views/sessions/path.js.erb中使用session[:path](而不是在app/assets/javascript的文件中)?如果是这样,那么您就走在正确的轨道上。

你说<%= p session[:path] %>什么都不"回报"。没错,因为p的返回值是 nil 。它打印你给它的东西,但它不返回任何东西。

我怀疑你的文件实际上正在渲染正确的Javascript,但什么也没发生,因为你应该说window.location = ...不是window.location.href = ...

编辑:顺便说一下,通常人们只有在以后的请求中再次需要时才将东西存储在session中。如果您只是尝试将变量传递给 JS 视图,您知道您可以使用实例变量,对吗?像这样:@redirect_path = conversation_url(conversation.id).