简体   繁体   中英

Rails life time of params variable

In the standard "index" method of controller I set some value in the params hash in order to use it in the view if it's not initialized yet in other case do nothing.

def index
  params[:my_value] ||= {}
end

when I use include? method on the params[:my_value] in the view, there's an error evaluating nil.include?

Why there's such error if params[:my_value] cannot be nil. If it's nil, its value should be initialized with {}, that's what ||= operator does. What can be the problem here?

The solution was in the merge method. It turned out that

a = b.merge(a) 

and

a.merge(b) {|key, v1, v2| v1 }

do different things and in the first case(which was wrong) nil appears somewhere. I haven't figured out yet why is it so because merge method always return a hash and when I replaced the first variant with the second everything was ok. So I don't see any problem...

rails parameters exists upto request flow completes

You can access params inside view page going to be rendered but params will not be available if you are doing re-direction to another page inside controller action as it interrupts request flow.

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