32. O/RM がなかったら
# 疑似コードです。
query = "SELECT id, name FROM users WHERE name = 'hoge'"
result = SQL.execute!(query)
if result.empty?
create_query = "INSERT INTO users VALUES ('hoge')"
SQL.execute!(create_query)
result = SQL.execute!(query)
end
update_query = "UPDATE users SET name = 'goro' where id = ?"
user = result[0]
SQL.execute!(update_query, user[:id])
48. クエリビルダ 例
class User < ActiveRecord::Base
scope :admin, -> { where(type: 'admin') }
scope :rank_max, -> { where(rank: 5) }
end
User.where(type: 'admin')
.to_sql # => where type = 'admin'
User.admin.to_sql # => where type = 'admin'
User.admin.rank_max.to_sql # => where type = 'admin'
# and where ranke = 5