How to access data sent by user using controller on Ruby on Rails

时光怂恿深爱的人放手 提交于 2019-12-06 09:28:51

问题


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 ?


回答1:


Params

The problem is you're trying to access the params hash in your view

This 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), the params are not available in there

When you receive the error:

undefined method `[ ]' for nil:NilClass

This basically says that your calling of [] on the params variable is not possible, as this object is nil (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



来源:https://stackoverflow.com/questions/24548698/how-to-access-data-sent-by-user-using-controller-on-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!