0
0

【Rails】link_toとPrefixと引数と【初心者】

Posted at

link_toでprefixで繋ぐ時、引数を何を渡せばいいのか

link_to自体のやり方はこちら

どういうものを作っているかによって変わると思うのだが
link_toでindexとnewに行く時は引数を基本使わない。
indexとかから、edit、show、destroyに行く時は基本使う。
editに行くとしてproductモデルで@products.each do |product|で回してるなら、
edit_product_path(product)とかedit_product_path(product.id)とかで、
editに引数を使ってproduct.idを渡して、editのコントローラーの方で
@product = Product.find(params[:id])で情報を全て拾う。
destroyの時だけmethod: :deleteをlin_toに入れる。
<%= link_to '削除' , product_path(product), method: :delete %>

1対多の時

1対多がproduct対reviewの時、
productのshowからreview新規作成したいぞって時、
@product.idをreviewの設定したproduct_idとしてlink_toでnewに飛ばす。
<%= link_to '新規作成' ,new_review_path(product_id: @product.id) %>
@product.idをproduct_idとしてnewに送っている状態
newのコントローラーの方で
@new = Review.new(product_id: params[:product_id])で拾ってくる
この時URLがhttp://localhost:3000/reviews/new?product_id=53
こんな感じに?product_id=id番号で出てたらしっかり渡せている。

0
0
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
0
0