親子関係のインスタンス、collectionオプション
親子関係にあるインスタンスの生成
def create # message投稿 # -> paramsに外部キー(room_id)が含まれる。 # -> 外部キーからRoomモデルのレコードを取り出す @room = Room.find(params[:room_id]) # 取り出したRoomのレコードが親要素、messagesが子要素 -> 繋げてnew # 子要素は複数形 @message = @room.messages.new() end
Rails.application.routes.draw do # 親子関係がルーティングされている resources :rooms, only: [:new, :create] do resources :messages, only: [:index, :create] end end
# 1対多 has_many class Room < ApplicationRecord has_many :messages end
collectionオプション
collection = 部分テンプレートrender × each
次の二つのコードは同義。
<!-- インスタンス変数 @hoges には複数の要素が入っている --> <% @hoges.each do |hoge|%> <%= render partial: 'hoge', locals: {hoge: hoge} %> <!-- 前半: 部分テンプhogeを読み込む --> <!-- 後半: @hogesから取り出した要素hogeを、hogeという名前で扱う --> <% end %>
<!-- 部分テンプレート内での要素名 = 部分テンプレート名 = hoge --> <!-- collectionオプションの対象 = 複数要素の入ったインスタンス変数 = @hoges --> <%= render partial: 'hoge', collection: @hoges %>