开发者

Ruby on Rails - What is the "Find" method?

开发者 https://www.devze.com 2023-02-06 22:21 出处:网络
@patient = Patient.fin开发者_Python百科d(17) Simply speaking, what does every single piece of this code is for?Simply saying: This will find patient data for id=17 and set it in @patient object.
@patient = Patient.fin开发者_Python百科d(17)

Simply speaking, what does every single piece of this code is for?


Simply saying: This will find patient data for id=17 and set it in @patient object.

Hope you understand it.


@patient is the instance variable of the class where this is called. Most likely this happens in your controller, then it's the instance variable of your controller called patient. @-char just indicates the instance variable part.

Patient. Rails follows ORM (object-relational mapping), which means that for every database table there is corresponding class. These classes that wrap database tables provide method that perform database table-level operations. Patient here is just the name of the class.

find is the class-level method provided by Patient class.

(17) is the parameter given to the find method. Rails will search patients-table and tries to find record with id = 17.


The above code fetches a record from the table ('patients' by rails convention) and assigns it to the @patient instance variable.

find is a method that is available to model Patient through inheritance from ActiveRecord::Base

The model Patient directly maps to a table in Database that you have configured in your database.yml The parameter 17 is matched with the primary key of the table and matching record is returned. Since it matches against primary key only a single record is found, returned.

If no record is found for value = 17, then a ActiveRecord::RecordNotFound exception is thrown.

0

精彩评论

暂无评论...
验证码 换一张
取 消