简体   繁体   中英

Rails session inside js erb empty

I want to use session[:path] inside js template,but it is empty

i have defined session[:path]='my path' and then want to put into js like

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

but return <%= p session[:path] => nil%>

controller

    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 template /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 %>

You should have session[:path] inside your path.js.erb file.

If you want to use some ruby variables inside your js files (like application.js) I would recommend gon gem

It sounds like you are using session[:path] inside app/views/sessions/path.js.erb (not within a file in app/assets/javascript )? If so you are on the right track.

You say that <%= p session[:path] %> "returns" nothing. That is right, because the return value of p is nil . It prints what you give it, but it doesn't return anything.

I suspect your file actually is rendering the right Javascript, but nothing is happening because you should say window.location = ... not window.location.href = ... .

Edit: By the way, usually people store things in session only if they are going to need it again in a later request. If you are just trying to pass a variable to your JS view, you know that you could use an instance variable, right? Like this: @redirect_path = conversation_url(conversation.id) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM