Three days ago I worked on a rails project. The fact is, I’m new to rails. Sure, there’re many trial and error, but I knew coding is like that, and then I have no big problem. Except for the error on that day. I actually faced the error for couple of days. Headache. Bump.
Really, what’s wrong?
I was working on a data retrieval, in rails it’s called active record. I added a new field for capturing calculation result from the other fields, so I called the field
price_change (note the _change here). I filled some values. I tried
rails console. I tested loading some data, it prints in the console. Let’s say I call the data to a variable named
stuff. Then I wanted to manipulate the
price_change of that
stuff, and it turns out I got a
0 (zero!). It’s totally different number than real number on the database. I tried to solve for couple of days, tried google, stackoverflow, I have no luck. What’s wrong with my code?
Fortunately, I stumbled upon to this site, Reserved Words in Ruby on Rails. Gotcha! Tough there is no reference to
_change, but I think I knew something.
something_change method will be created to every activerecord fields, It serves as a hook as well as capturing field behavior. If I have a field called
price, rails will create
price_change automatically. Then, yeah, I had a field called
price beside the
price_change. I finally proved this via simple
.methods from the particular object.
- Always check the method names carefully
- Always look
yourobject.inspect. And, every things in ruby is object. So be careful, and have fun.
- And finally, take a look at the
- Always check documentations.
Have a nice weekend. Happy coding!