从视图中设置一个cookie,然后从Rails中的Controller中读取它 [英] Set a cookie from view, then read it from Controller in Rails

查看:90
本文介绍了从视图中设置一个cookie,然后从Rails中的Controller中读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Javascript在Rails视图中设置cookie值,然后使用Controller读取此cookie。 Rails是否有可能,我应该如何处理?

I would like to set cookie value from within Rails view using Javascript, then use Controller to read this cookie. Is this possible with Rails, and how should I go about it?

我的情况:我有一个输入字段(例如地址),用户在输入s时需要填写/他首先来到我的网站。然后,用户使用Omniauth登录。我想一直保持住地址直到他登录。

My situation: I have an input field (say, address) that user needs to fill out when s/he first comes to my site. The user then logs in using Omniauth. I would like to persist address until after he logs in.

更新:
我能够在客户端上添加到document.cookies。但是,cookies [ something]从Rails结束返回nil。以下是Cookie哈希:

Update: I was able to add to document.cookies on client. However, cookies["something"] returns nil from Rails end. Below is the cookie hash:

#< ActionDispatch :: Cookies :: CookieJar:0x007 @ secret = f4d518c0b2,@ set_cookies = { },@ delete_cookies = {},@ host = localhost,@ secure = false,@ closed = false,@ cookies = { _ myapp_session => BAh7Ck ==-776b2fcfcd63d3c84d2b1de5327e277499add6d4, fbsr_150gt; 885> mqZeyvoRC},@ signed =#< ActionDispatch :: Cookies :: SignedCookieJar:0x007 @parent_jar =#< ActionDispatch :: Cookies :: CookieJar:0x007fdf ...> ;, @verifier =#< ActiveSupport :: MessageVerifier:0x007fdfa34548d8 @ secret = f4d518c0b2e9d8,@ digest = SHA1,@ serializer = Marshal>>><

推荐答案

要在javascript中设置cookie,您可以执行以下操作:

To set a cookie in javascript you can do:

document.cookie = something = test;

因此您可以添加一个事件(单击,提交,..)以从输入中获取值并按照我提到的方式创建cookie

So you can add an event (click, submit, ..) to get the value from the input and create a cookie the way i mentioned above.

在rails中,您可以读取以下值:

In rails you can read the value like this:

cookies [ 某物]

如果需要,您还可以在JavaScript中指定cookie何时过期。

这篇关于从视图中设置一个cookie,然后从Rails中的Controller中读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆