【问题标题】:Rails - Trying to set cookies from Create ActionRails - 尝试从创建操作设置 cookie
【发布时间】:2011-10-23 08:22:54
【问题描述】:

我正在尝试为未在表单的创​​建操作中登录的用户设置 cookie。一旦未登录的用户点击提交,他们就会被重定向到登录/注册操作,然后他们会返回到他们之前所在的页面,并且表单会自动填充他们之前输入的信息。

我已成功添加 cookie,它们正在保存,但它们返回一个奇怪的字符串对象。

"{\"1\"=>\"This is a test answer\"}" # 1 is the question_id and 'This is a test answer' is the answer_text

这是我设置 cookie 的创建操作:

def create 
  store_location  

 if current_user.nil?
   cookies[:answer_entry] = { :value => params[:answers] }
   # raise p cookies[:answer_entry].inspect 
   deny_access
 else 
   params[:answers].each do |question_id, answer_text|
     next if answer_text.blank?
     question = Question.find(question_id)
     question.answers.create!(:answer => answer_text, :user_id => current_user )
     raise p question.answer
     redirect_to book_questions_path(@book), :notice => "You have successfully submitted your Answer, please answer more!"
   end
  end 
end

然后我将 cookie 保存到 show 操作中的一个实例变量(这是表单出现的地方),然后将变量作为表单中的值传递:

def show
  @book = Book.find(params[:book_id]) 
  @question = @book.questions.find(params[:id])

  if user_signed_in?
    @answer = cookies[:answer_entry]
  else
   cookies[:answer_entry] = nil 
  end
end 

还有

<%= form_for(:answer, :url => book_question_answers_path(@book, @question)) do |f| %>
  <%= text_area_tag "answers[#{@question.id}]", @answer%>
  <%= f.hidden_field :user_id, :value => @current_user %> 
  <%= submit_tag("Submit") %>
<% end %>

由此,我在表单字段中自动填充了那个奇怪的字符串。

我有两个问题:

  1. 我知道这是一个字符串 "{\"1\"=>\"This is a test answer\"}" 但是有人能解释为什么里面有一个散列以及为什么双引号被转义吗?
  2. 我只想在表单字段中呈现 answer_text(“这是一个测试答案”),有人能指出我正确的方向来解决这个问题吗?我是否必须拆分字符串并将其重新分配为哈希,然后调用 :answer_text 参数?

我感谢任何和所有的帮助。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby string cookies


    【解决方案1】:

    您将哈希存储在 cookies[:answer_entry] 中,这就是为什么当您检索它并将其存储在 @answer 实例变量中时,您会返回一个哈希,而当您在 text_area_tag 中使用它时,它会显示为一个字符串。

    有几种方法可以解决这个问题

    一种方式

    在创建操作中分配给 cookie[:answer_entry] 如下

    cookies[:answer_entry] = params[:answers]
    

    方法二

    在显示操作中从 cookies[:answer_entry] 中检索值,如下所示

    @answer = cookies[:answer_entry][:value]
    

    【讨论】:

    • 感谢您的快速响应,但当我这样做时,我得到:undefined method symbolize_keys!'对于 {"1"=>​​"asdadad"}:ActiveSupport::HashWithIndifferentAccess` 并通过两种方式得到:can't convert Symbol into Integer。我是否也必须更改视图中的某些内容?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多