Boost your Rails Controller params[:fu]
In many ways, in a Rails controller POST action, what gets POST-ed in params are often overlooked. In many straight-forward tutorials, we slap a forms_for @customer in our view, and then the params will come out to be directly consumable by our ActiveRecord model. Unfortunately, many new Rails developers cannot see beyond the usefulness of hashing the posted parameters accordingly. In the next few blog posts, I intend to show you that if you take the time to assemble your params the way Rails likes it, you can dramatically reduce the amount of code you have to write in your controller actions and models, simply because Rails takes care of it for you. The end result is getting it done in less code, fewer tests, less trouble.
Here it goes, the params[:fu] series:
- params[:fu] # => "1" Wrap all relevant attributes in a single params key.
- params[:fu] # => "2" Put attributes into a different params key using fields_for if they belong to different models.
- params[:fu] # => "3" Using fields_for and the index option to create a new parent model with multiple child models.
- params[:fu] # => "4" Use the magical <association_name>_ids=([...array of ids]) association proxy method.
- params[:fu] # => "5" Use ids to update multiple models in update action atomically.
update:
These tips have been chosen as the 8th runner-up in the Railscasts 100th episode contest. And for that, let me add another parmas[:fu] bonus to this list to all readers:
- params[:fu] # => "bonus" Passing multiple params in an observe_field, now that you know your parmas[:fu].
Enjoy!
3 comments:
Thanks a lot Stephen! I thought I had this stuff covered, but I've learned something new on #5.
Very nice collection of posts!
thank you so much, it is really helpful, keep up with more tutorials.
the one that helped me a lot is the parent -> multiple childs.
Post a Comment