Rails Idiocy - When Params In Your Controller Are Nil

 1 year ago
source link: https://fuzzyblog.io/blog/rails/2017/04/12/rails-idiocy-when-params-in-your-controller-are-nil.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails Idiocy - When Params In Your Controller Are Nil

Apr 12, 2017

So I got up early and got cracking on some code and then I hit an absolute wall – the kind of thing that just stops you cold. I was debugging a controller in my side project and I got a nil on accessing a member on the params hash. And since this was something I'd done previously I thought it odd but added debugger to my controller and evaluated params:

[12, 21] in /Users/sjohnson/Dropbox/fuzzygroup/hyde/seira_watch_web_app/app/controllers/instructors_controller.rb
   12:   end
   14:   def create
   15:     @instructor = Instructor.new# => (params[:instructor])
   16:     debugger
=> 17:     if params[:instructor][:url] =~ /http/
   18:     else
   19:       flash[:error] = "Please specify a valid url"
   20:       redirect_to edit_instructor_path(@instructor) and return
   21:     end
(byebug) params

A decade plus in Rails and Ghu only knows how many controllers and I don't think I've ever seen nil for params. I mean params is effectively a god object that is always there. How the hell does it become nil?

This was when I put my keyboard down, went over to my editor and started doing some writing. I knew in my gut that this was an oddball issue and what I really needed was another set of eyes. And, an hour later, my buddy Nick, gave me a hand over Google Hangouts pointing out that I had something wrong my strong params method:

def instructor_params

The above code is lexically correct and won't cause any errors but it will absolutely screw everything up and make params goto nil. This should have been:

def instructor_params

The difference between [ ] and () is of course very, very real but it is subtle, particularly from a visual angle where you can easily mistake them.

Posted In: #rails

About Joyk

Aggregate valuable and interesting links.
Joyk means Joy of geeK