Many people new to Rails, myself included, wonder: Where or how do I access form post data?
You know, the stuff that gets sent to the HTTP server from a user?
The answer is surprisingly simple, but often overlooked in books and tutorials that focus on Ajax and Javascript silliness. Post data goes into an array called params
This is a pretty crucial tool for accessing things. A confusing aspect is all the form helper methods available in the ActionView part of the Rails API. Yes, you do need to keep a web browser open to api.rubyonrails.org and look stuff up frequently. That’s life. Fortunately for you, the Rails API is pretty well documented these days. Anyway, you access the data in params as an array element where the element name is a Ruby symbol. (symbols are a little weird, but suffice it to say that they exist as unique identifiers of things in Ruby) params[:name] corresponds to some form element with a name attribute set to “name” such as a <%= text_field_tag("name", "person") %>.
One thing you need to do is edit your view rhtml and then load it in a browser to see how things get rendered from the various Rails form helpers and stuff. The final rendering will give you an idea of what your params array accessor should look like.
Then in your corresponding controller and its corresponding method (the method that handles the form) you can assign the params array data to instance variables and do things with that data.
Well, if you’re still relying on scaffolding, that might be one thing that is confusing you. The scaffolding is useful for generating a basic CRUD app that has the ability to interact with the database from a web page. That’s it. All other stuff is added by you.
Rails likes to use instance variables. In Ruby, that’s a variable with the @ sigil: @variable_name. So, in your controller you can do a lot with the data in an instance variable just using straight Ruby code. This is why you need to know Ruby before using Rails, because you will be using Ruby to do anything at all with Rails beyond the scaffolding.
Rails is a bit mystifying for people new to it. Any framework is. The fog is clearing a bit for me lately.
4 comments ↓
This was exactly what I was looking for. Thanks!!
Yes!, you are right. This is a pretty crucial tool and mostly obviated by books and tutorials. I was needing to confirm a suspicion that I had and your post gave me the confirmation. Thanks a lot.
Your so, so right. I am a bit flustered right now :)
I’ve just been looking at Rails2, and it’s been a long time since I’d touched Rails. (about a year)
Boy is it different in ways that count. A lot is familiar, but a lot of the basics are flat out DIFFERENT in unintuitive ways.
Time to pick up Patrick Lenz’s Simply Rails2 !
His first book was the most plain-language intro.
Leave a Comment