我正在使用 cookie 来存储用户选择的国家/地区。只有两个选择 - 拉脱维亚或爱沙尼亚。
问题是,有时当我想更改国家/地区时,它会起作用。但有时我无法随心所欲地点击,但国家/地区不会改变。其他时候,按 F5 或刷新之前选择的国家/地区会更改为其他国家/地区。
到目前为止我的代码。
Application_controller.rb
before_filter :set_location
def set_location
if cookies[:estonia] == '1'
@location = Country.find(2)
elsif cookies[:latvia] == '1'
@location = Country.find(1)
else
if request.location.country == 'Latvia'
@location = Country.find(1)
elsif request.location.country == 'Estonia'
@location = Country.find(2)
else
@location = Country.find(1)
end
end
end
在布局中
<script language="JavaScript">
function latvia(){
days=1; // number of days to keep the cookie
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'latvia=1; expires=' + myDate.toGMTString();
document.cookie = "estonia=1; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
function estonia(){
days=1; // number of days to keep the cookie
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'estonia=1; expires=' + myDate.toGMTString();
document.cookie = "latvia=1; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
</script>
和位置选择:
<% if @location.id == 1%>
<li> <%= link_to "Igaunija ", root_path, :onclick => 'estonia()'%></li>
<%else%>
<li> <%= link_to "Latvija ", root_path, :onclick => 'latvia()'%></li>
<%end%>
此更改基于已选择的可用位置选项。
在 Mozilla firebug 中,我看不到任何与 cookie 相关的错误。 当我清理网站数据(例如 Cookie 和历史记录)时,它会再次正常工作一段时间。
那么什么会导致这些问题呢?
提前致谢!
最佳答案
了解您的需求有点困难,但我会省略 javascript 部分并仅使用 Rails 设置这些 cookie。我想您需要提供默认国家/地区,但我不确定为什么需要将其设置为 root_path
。
我不会使用这些神秘的 ID key 来确定位置,而是使用符号 country: :latvia
、country: :estonia
。
我想这完全取决于您的用例。
# View
<% if @location.id == 1%>
<li> <%= link_to "Igaunija ", root_path(country_id: 1) %></li>
<%else%>
<li> <%= link_to "Latvija ", root_path(country_id: 2) %></li>
<%end%>
# Controller
before_filter :set_location
def set_location
@location = Country.find(current_location_id)
cookies[:country_id] = @location.id
end
def current_location_id
params[:country_id] || cookies[:country_id] || 1
end
硬编码“1”不是一个好的做法。我会使用国家/地区符号::en、:lv、:est 然后,您可以创建一个返回默认位置的方法,而不是“1”。
Country.default_location #=> :lv
关于javascript - 使用 Rails 4 将用户选择的国家/地区存储在 cookie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27568832/