[Rails-core] RFC: Safely accessing the params hash

Michael Schuerig
2005-08-08T04:50:35Z

For has_(and_belongs_to_)many associations, I use nested hashes/arrays
in @params (ActionController#params). Thus, @params may look like this

{ :id => 1,
  :employee => { :lastname => "new lastname"
                 :task_ids => [1, 2, 3] }
}

Of course, I''d like it best if new/create/update_attributes would
handle
this automatically behind the scenes, i.e., call employee.task_ids =
[1, 2, 3]. (A)

As this is not the case (yet), I have to handle this case manually in
controllers:

  employee.task_ids = params[:employee][:task_ids]

On a sunny day it''ll even work. As params[:employee] can be nil,
there''s
a lurking failure. As a solution, I propose to implement params
explicitly like this (B)

  def params(*args)
    if args.empty?
      @params
    else
      default_value = nil
      if args.last.kind_of?(Hash)
        opts = args.pop
        default_value = opts[:default]
      end
      @params.get_at_path(args) || default_value
    end
  end

Not shown here is the implementation of get_at_path. For that I have
mixin (C) that works with hashes, traversing keys, as well as ordinary
objects, traversing methods. I find this *very* useful not only in this
particular case.

I''m looking forward to your comments. If there''s interest,
I''ll
write/submit patches for (A), (B), (C).

Michael

--
Michael Schuerig                             Those who call the shots
mailto:michael@schuerig.de              Are never in the line of fire
http://www.schuerig.de/michael/           --Ani DiFranco, Not So Soft