Rails:表单提交后在视图中访问参数 [英] Rails: Access parameters in view after form submission

查看:86
本文介绍了Rails:表单提交后在视图中访问参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Rails 3.2 项目中,我有一个表单可以在 app/views/sites/

new.html.erb 中创建一个新站点

<%= form_for(@site) do |site_form|%>...<div class="field"><%= site_form.label :hash_name %><br/><%= site_form.text_field :hash_name %>

...<div class="actions"><%= site_form.submit %>

<%结束%>

然后是sites_controller.rb

中的create函数

def 创建@site = Site.new(params[:site])response_to do |格式|如果@site.saveformat.html { redirect_to @site }别的format.html { 渲染动作:新"}结尾结尾结尾

然后在用户提交之后,我想在show.html.erb

中展示用户刚刚提交的hash_name

你只需输入 <%= params[:hash_name] %>.

但是访问 params[:hash_name] 不起作用.我如何访问它?

解决方案

您正在重定向到不同的操作 - 这将重置您传递给 create 操作的所有参数.

要么像其他答案一样将 hash_name 作为参数传递,要么直接从 @site 对象中获取它.

In my Rails 3.2 project, I have a form to create a new site in new.html.erb in app/views/sites/

<%= form_for(@site) do |site_form| %>
  ...
  <div class="field">
    <%= site_form.label :hash_name %><br />
    <%= site_form.text_field :hash_name %>
  </div>
  ...
  <div class="actions">
    <%= site_form.submit %>
  </div>
<% end %>

Then the create function in sites_controller.rb

def create
  @site = Site.new(params[:site])

  respond_to do |format|
    if @site.save
      format.html { redirect_to @site }
    else
      format.html { render action: "new" }
    end
  end
end

Then after the user submits, I want to show the hash_name that the user just submitted, in show.html.erb

You just put in <%= params[:hash_name] %>.

But accessing params[:hash_name] doesn't work. How can I access it?

解决方案

You're redirecting to a different action - this will reset all the parameters you passed to the create action.

Either pass hash_name as a parameter like the other answer suggests, or just fetch it straight from the @site object.

这篇关于Rails:表单提交后在视图中访问参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆