LoginSignup
0

posted at

Formオブジェクトで保存したデータを表示させるには

formオブジェクトで複数テーブルに保存したデータをページ上に表示させるのに苦労したので、忘備録として記録する。

formオブジェクトのデータを取得したい

itemテーブルとmaterialテーブルがあったとする。
二つのテーブルを組み合わせて、Item_materialクラスを定義した。

詳細ページにて、materialテーブルに保存したデータを表示するためにitemコントローラーに下記を記述した。

def show
  @item = Item.find(params[:id])
  @material = Material.find(params[:id])
end

これではダメたった。material.idが@itemと同じidを取得してしまう。
例えばitem.idが4ならmaterial.idも同じ4になる。

成功したコード

def show
  @item = Item.find(params[:id])
  @material = @item.material
end

これでいけた。この記述なら@itemが持ったmaterial情報を取得できる。

ビューへの記述は@material.カラム名でOK

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
What you can do with signing up
0