如何访问用户在Ruby on Rails上使用控制器发送的数据 [英] How to access data sent by user using controller on Ruby on Rails
问题描述
我在保存用户发送的数据并在我的视图文件中使用它时出现问题,我找不到其他主题的解决方案。
我的代码通过表单选择日期:
<%= select('resource','field',@benchmark .compositions.find(:all).collect {| u | [u.date_composition]},:prompt =>'Selected date')%>
这是我的控制器来获得这个选择:
def sample_method
@resource_field = params [:resource] [:field]
end
这是我在routes.rb文件中的行:
match'benchmark / sample_method /:resource /:field',:controller => 'benchmarks',:action => 'sample_method'
现在我想在我的视图中使用所选的值,
<%@resource_field = @ benchmark.find(params [:resource] [:field])%>
但它说
ActionView :: Template :: Error(未定义的方法`[]'for nil:NilClass)
$ b b
如何使用我选择的值?
问题是您尝试访问视图中的 params
哈希
这将不起作用,因为 params
是从请求发送到您网站的 HTTP值 - 只有可用基于每个请求。由于您的视图本质上是另一个请求(类似重定向), params
在其中不可用
当您收到错误:
未定义方法`[]'for nil:NilClass
这基本上说你在 params
变量上调用 []
是不可能的,因为此对象 nil
(未填充数据)
-
变量
您需要做的是在控制器中设置数据 MVC编程模式(您应该永不必须在视图btw中使用 ActiveRecord
方法:
#app / controllers / your_controller.rb
pre>
Class YourController< ApplicationController
def action
@resource_field = @ benchmark.find params [:resource] [:field]
end
end
这应该使您的数据可用,而使用刚刚传递给Rails的
params
I have a problem saving data sent by a user and using it in my view file, and I can't find a solution in other topics.
This is my code to select a date via a form:
<%= select( 'resource', 'field', @benchmark.compositions.find(:all).collect {|u| [u.date_composition] }, :prompt => 'Selected date') %>
This is my controller to get this selection:
def sample_method @resource_field = params[:resource][:field] end
And this is my line in the routes.rb file:
match 'benchmark/sample_method/:resource/:field', :controller => 'benchmarks', :action => 'sample_method'
Now I'd like to use the selected value in my view, so I put:
<% @resource_field = @benchmark.find(params[:resource][:field]) %>
But it says
ActionView::Template::Error (undefined method `[ ]' for nil:NilClass)
How can I use my selected value please ?
解决方案The problem is you're trying to access the
params
hash in your viewThis won't work, as the
params
are HTTP values sent from a request to your site - only being available on a per-request basis. As your view is essentially another request (kind of like a redirect), theparams
are not available in thereWhen you receive the error:
undefined method `[ ]' for nil:NilClass
This basically says that your calling of
[]
on theparams
variable is not possible, as this object isnil
(not populated with data)--
Variables
What you'll have to do is set your data in your controller, as per the MVC programming pattern (you should never have to use
ActiveRecord
methods in your views btw):#app/controllers/your_controller.rb Class YourController < ApplicationController def action @resource_field = @benchmark.find params[:resource][:field] end end
This should make this data available in your view, whilst using the
params
which have just been passed to Rails这篇关于如何访问用户在Ruby on Rails上使用控制器发送的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!