LoginSignup
2
2

More than 5 years have passed since last update.

Rails勉強備忘録

Last updated at Posted at 2016-04-04

知り合いがまとめてくれた記事。
http://qiita.com/runamoon@github/items/5277970364dca43b1204

ActiveRecord::Aggregations::ClassMethods

バリューオブジェクト関連のメソッド。

class Customer < ActiveRecord::Base
  composed_of :balance, class_name: "Money", mapping: %w(balance amount)
  composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
end

ActionDispatch::Routing::Mapper::Concerns

concern :commentable do
  resources :comments
end

concern :image_attachable do
  resources :images, only: :index
end

resources :messages, concerns: [:commentable, :image_attachable]

ActiveModel::AttributeMethods::ClassMethods

alias_attribute(new_name, old_name)

class Person
  include ActiveModel::AttributeMethods

  attr_accessor :name
  alias_attribute :nickname, :name
end

person = Person.new
person.name = 'Bob'
person.name            # => "Bob"
person.nickname        # => "Bob"

ActiveRecord::Associations::ClassMethods

Polymorphic Associations の実装方法

class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
end

class Post < ActiveRecord::Base
  has_many :assets, as: :attachable
end

ActiveRecord::AttributeMethods::Serialization::ClassMethods

serialize のデフォルトはYAML

class User < ActiveRecord::Base
  serialize :preferences, JSON
end

class User < ActiveRecord::Base
  serialize :preferences, Hash
end

ActiveRecord::Store

serialize のラッパー。

class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ], coder: JSON
end

ActiveRecord::Querying

find_by_sql の戻り値は配列

ActiveRecord::Batches

find_in_batches のオプションは batch_size と start

ActiveSupport::Testing::Assertions

assert_difference の書き方は3パターン

assert_difference 'Article.count' do
  post :create, article: {...}
end

assert_difference [ 'Article.count', 'Post.count' ], 2 do
  post :create, article: {...}
end

assert_difference ->{ Article.count }, 2 do
  post :create, article: {...}
end

Rails 固有のアサーション

  • assert_difference
  • assert_no_difference
  • assert_recognizes
  • assert_generates
  • assert_response
  • assert_redirected_to
  • assert_template
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2