Ruby/rails/db関連付け
提供: 初心者エンジニアの簡易メモ
関連付け一覧
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