Last active
August 23, 2018 22:34
-
-
Save srockstyle/3d7dbe730524335eee7846c6448773f9 to your computer and use it in GitHub Desktop.
[WIP] ActiveRecordの使い方リスト:その2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## scope | |
# scopeさんはよくつかうであろう検索条件を書いておくことができます。これをやることで毎回同じこと書かずに済みます。 | |
scope :rock_artist_search,where(genre: "rock") | |
Artist.rock_artist_search | |
## ids | |
# レコードのidだけをとってきます | |
Artist.ids | |
## pluck | |
# 任意のカラムの配列を返してくれます | |
@artists_name = Artist.pluck(:name) | |
# => ["Oasisi","Queeen","Cold Play"] | |
##---------------- | |
# 書き込み系 | |
##---------------- | |
# save | |
# saveはModel.newからデータをいれたものを保存。戻り値はtrueかfalse | |
artist = Artist.new(params_artist) | |
artist.save | |
# -> true | |
# update/update_all/update_attributes/update_attribute/update_column | |
# こいつらはupdateする系なんですが、update_attributeとかはupdateのエイリアスになってるみたいなので、まとめて紹介。 | |
# 使い方はモデルに対して値を設定します。 | |
Artist.update("name = 'Oasis'") | |
#一部を取得してupdate。 | |
@artist.update_column(:name = "OASIS") | |
# destroy/delete/destroy_all/delete_all | |
# こいつらは削除してしまいます。 | |
@artist = Artist.find(1) | |
@artist.destroy | |
## => 消える | |
# increment | |
# レコードのIDや番号のものをインクリメントしてくれます。テーブルを複数DBに分けたりするときに役立ちそうとか思うのはインフラエンジニア出身だからでしょうか。 | |
Artist.increment(:id,4) | |
# attribute_present?/has_attribute? | |
# カラムがあるかチェックしてくれます。 | |
Artist.attribute_present?(:debut_date) | |
#=> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment