简体   繁体   中英

Rails - How to access a Request Parameter from view in a helper

How do you access a view's request parameter inside a Helper?

My view events/index7 sets the parameter date_selected:

<div><%= link_to 'View' , events_index7_path(:date_selected => date), :class => 'btn  btn-mini'%></div>

My helper is app/helpers/calendar_helper.rb

Here's a pic of it at the point in the Helper I where I want to access it.

在此处输入图片说明

I tried this:

classes << "dayselect" if day == DateTime.strptime(params[:date_selected], "%Y-%m-%d")

I get this error:

undefined local variable or method `params' for #<CalendarHelper::Calendar:0x007f8d215671f0>

OR should I be passing the date to the helper in a different way?

Thanks for the help!

params is a controller method, belongs to ActionController:Metal http://api.rubyonrails.org/classes/ActionController/Metal.html#method-i-params

It's possible to let View to touch params by exposing this controller method as a helper.

class FooController < ApplicationController
  helper_method :params

Then, in your view you can call this helper with params as argument. my_helper(params)

But, wait, this breaks MVC principle . View should not touch params at all. All these works should be done at controller level. What if the params is incorrect? You need controller to respond that, instead of passing that responsibility to view.

So, if you need to touch it in view, it's a smell. Review the whole process, there must be a better arrangement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM