0
0

More than 1 year has passed since last update.

【Rails】link_toで移行先のアクションにパラメータを渡す方法

Posted at

環境

  • Mac(12.2.1)
    • MacBook Pro (13-inch, 2020)
    • 2 GHz クアッドコアIntel Core i5
    • 16 GB 3733 MHz LPDDR4X
  • ruby (3.0.0p0)
  • rails (7.0.1)

解決したい内容

Rails link_toにパラメータを渡す

link_toを使ってgetsでコントローラにパラメータを受け渡したい

やりたいこと

view側からコントローラにリンクする際に、値を受け渡したい

以下のようにパスの引数にハッシュの形で追加してやる

※例)top/indexからtop/link1へ値を渡す場合

top/index.html.erb
  <%= link_to "リンク1へ", top_link1_path(name: "piyo") %>

パラメータを受け取る

top_controller
class TopController < ApplicationController
  def link1
    @params = params[:name]
  end
end
app/views/egograms/_egogramindex.html.erb
・
・
・
<%@index.each do |i|%>
<% number=i.test_result_id%>


<%=test_result_number=TestResult.find(number).id%></br>
<!-- このTestResult.find(number)を
redirect toする時にparamsに値を入れて
showアクションに飛んでegogram_resultのレイアウトを使用して
該当する結果を表示-->

<%= link_to "この結果のshow",egograms_show_path(id: test_result_number) %>
・
・
・
app/controllers/egograms_controller.rb
def show
 #paramsで「(id: test_result_number)」の「(test_result_number)」の値が「[:id]」に入る
  @result=params[:id]
  render :result
end



参考にした記事

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