「Ruby/rails/db関連付け」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→1:n) |
(→命名規則が使えない場合の1:n紐付け) |
||
(同じ利用者による、間の5版が非表示) | |||
行6: | 行6: | ||
has_one :through | has_one :through | ||
has_and_belongs_to_many | has_and_belongs_to_many | ||
+ | |||
+ | ==belongs_to関連付けオプション== | ||
+ | :autosave | ||
+ | :class_name | ||
+ | :counter_cache | ||
+ | :dependent | ||
+ | :foreign_key | ||
+ | :primary_key | ||
+ | :inverse_of | ||
+ | :polymorphic | ||
+ | :touch | ||
+ | :validate | ||
+ | :optional | ||
==1:n関連のデータ取得例== | ==1:n関連のデータ取得例== | ||
行19: | 行32: | ||
logger.debug("battle.user.name=#{battle.user.name}") | logger.debug("battle.user.name=#{battle.user.name}") | ||
end | end | ||
+ | |||
+ | ==1:1関連のデータ取得例== | ||
+ | class Supplier < ApplicationRecord | ||
+ | has_one :account | ||
+ | end | ||
+ | class Account < ApplicationRecord | ||
+ | end | ||
+ | |||
+ | acounts = Account.all | ||
+ | acounts.each do |account| | ||
+ | logger.debug("account.supplier.name=#{account.supplier.name}") | ||
+ | end | ||
+ | |||
+ | ==命名規則が使えない場合の1:n紐付け== | ||
+ | battles.battle_user_idをusers.idと紐づける | ||
+ | class User < ApplicationRecord | ||
+ | has_many :battle | ||
+ | end | ||
+ | class Battle < ApplicationRecord | ||
+ | belongs_to :user | ||
+ | belongs_to :battle_user, class_name: "User" | ||
+ | end | ||
+ | |||
+ | battles = Battle.where("user_id = ?", params[:id]) | ||
+ | battles.each do |battle| | ||
+ | logger.debug("battle.user_id=#{battle.battle_user.name}") | ||
+ | end | ||
+ | |||
+ | ==参考== | ||
+ | 公式rails関連付け:https://railsguides.jp/association_basics.html |
2017年11月17日 (金) 07:35時点における最新版
関連付け一覧
belongs_to has_one has_many has_many :through has_one :through has_and_belongs_to_many
belongs_to関連付けオプション
:autosave :class_name :counter_cache :dependent :foreign_key :primary_key :inverse_of :polymorphic :touch :validate :optional
1:n関連のデータ取得例
class Battle < ApplicationRecord belongs_to :user end class User < ApplicationRecord has_many :battle end
battles = Battle.where("user_id = ?", params[:id]) battles.each do |battle| logger.debug("battle.user.name=#{battle.user.name}") end
1:1関連のデータ取得例
class Supplier < ApplicationRecord has_one :account end class Account < ApplicationRecord end
acounts = Account.all acounts.each do |account| logger.debug("account.supplier.name=#{account.supplier.name}") end
命名規則が使えない場合の1:n紐付け
battles.battle_user_idをusers.idと紐づける
class User < ApplicationRecord has_many :battle end class Battle < ApplicationRecord belongs_to :user belongs_to :battle_user, class_name: "User" end
battles = Battle.where("user_id = ?", params[:id]) battles.each do |battle| logger.debug("battle.user_id=#{battle.battle_user.name}") end
参考
公式rails関連付け:https://railsguides.jp/association_basics.html