2
1

More than 3 years have passed since last update.

[rails]ネストした関係で親情報を子ビューに表示する方法

Last updated at Posted at 2020-09-06

やりたいこと

前提・Itemの情報がないとOrderの情報は成り立たない関係
(Orderにitem_idカラムがある(どのitem情報を指しているのか?))
(親)itemテーブル>(子)orderテーブルになる。

orderコントローラでindexアクションを起動させ(index.html.erb)に
(親)のitem情報を表示させたかったらどうやって記述するの?
※例えば
itemテーブル     
id:1
ぬいぐるみ4000円

orderテーブル
item_id:1
user_id:3
ぬいぐるみ4000円とuser_idが結びつくんだな・・・

手順

config/routes.rbの記述内容
Rails.application.routes.draw do
   devise_for :users
  root  'items#index'
  resources :items do
    resources :orders, only: [:create, :index]
  end
end

1.親items>子ordersの関係をroutes.rbで記述する

resources :items do
    resources :orders, only: [:create, :index]

これで(親)item>(子)orderの関係を指定することができる。ネストすることができる

2.ordersコントローラーで@item = Item.find(params[item_id])と記述する

def index
     @item = Item.find(params[:item_id])
  end

@itemの箱の中にitemテーブルの情報を入れる。
どのitemテーブルの情報を指定するか[:item_id]で指定できる
ユーザーが選択したitem情報を@itemに代入する

3.@itemをorder#indexのビューファイルに記述する

orderコントローラーのindex.html.erbに記述
<%= @item.item_name %>

これで(親)itemテーブルからデーターを抜き出して
(子)orderコントローラーのindex.html.erbのビューに表示することができる。

まとめ

分かりにくいまとめですが
要は親テーブルの情報を抜き出して、子のビューに表示させたかったら
ネストを使って関係を示し、子コントローラーでparams[:親_id]と記述すれば
親から情報を抜き出して子のビュー表示することができるという内容でした。

うまくまとめることができないのは私の力不足です・・・。
具体的な画像とテーブル情報が添付していると分かりやすくなったかも。

2
1
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
1