Thanks to some metaprogramming magic, whenever you create a column within a table, you get a free
find_by_[name of column] method.
Create a new Friend model with a name and address:
rails g model Friend name:string address:string
find_by_[name of column]
If you use Rails Command Line to create a model, then you get this method for free.
Query a friend by their name:
f = Friend.find_by_name("name of friend")
Query a friend by their address:
f = Friend.find_by_address("5555 Disney Ave, Los Angeles, CA")
Query a friend by their database ID:
# f = Friend.find(1) f = Friend.find(params[:id])
Query everyone in the database:
f = Friend.all
You also get a
LIKE operator for situations where you only have a partial address:
a = Friend.where("address ILIKE ?", "%partial address%")
This is only for very specific circumstances but you can also create a raw SQL command.
Friend.find_by_sql "enter your specific SQL query"