Rails

Rails routing ; namespace

namespace コントローラの数が増えてきて、下のように コントローラをディレクトリ分類したくなったときに使う。 controller/admin/task_controller.rb controller/user/task_controller.rb ... Sampleapp::Application.routes.draw do namespace :admin do …

Rails Model の scope 3系 と 4系

3系 と 4系で違い scope の書き方が変更されている。 (lambda の処理が関係してそう) DEPRECATION WARNING: Using #scope without passing a callable object is deprecated. For example `scope :red, where(color: 'red')` should be changed to `scope :r…

ActiveRecord new_record?

ActiveRecord の new_record? まだ save されていない record だったら true を返す。 違っていれば false。 厳密には、一つのレコードに対するオブジェクトが ストア(保存) されていなければ true 違えば false https://github.com/rails/rails/blob/260471…

find と find_by の違い

ActiveRecord::FinderMethods より モノが違うので一言では書けないです 概要 #find(*arg) 正常系処理 実引数の値はテーブルのプライマリーキーに対応していることを期待 甲. find(value) 値を WHERE 句で条件制約して SELECT する値がテーブル中に存在する…

save/save! create/create!

前提情報 create_table "products", force: true do |t| t.string "title" t.text "description" t.string "image_url" t.decimal "price", precision: 8, scale: 2 t.datetime "created_at" t.datetime "updated_at" end class Product < ActiveRecord::Bas…

new と build

自身で改めて class Cart < ActiveModel has_many :line_items end class LineItems < ActiveModel belongs_to :cart end [1] Cart.new は OK Cart.build は NG [2] c = Cart.new して c.line_items.new, c.line_items.build は OK [3] そもそも build は ne…

find と find_by の違い と 補足

概要 User のレコードに、存在しない session[:id] を find, find_by したとき User.find(999) #=> ActiveRecord::RecordNotFound User.find_by(id: 999) #=> nil になる。 ファインダ find id などの主キーに find する、ということは 目的のレコードが存在…

bundle install して rubygems.org に SSH 接続できない時

経緯 rails new foo して bundle install したら Unable to download data from https://rubygems.org/ - SSL_connect のようなエラーが出る 原因 rvm が最新版ではなかった 解決手順 rvm get stable して bundle install したら難なく ディストリ ごとに挙…