How to access data sent by user using controller o

2019-04-13 05:59发布

问题:

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