LoginSignup
8
1

More than 1 year has passed since last update.

【Ruby on Rails】クエリパラメータの使い方

Posted at

・クエリパラメータとは

# クエリパラメータの例
https://localhost:3000/work?day=1024

?以降がクエリパラメータ。
上記だと
「test」がキー
「1024」が値。

・複数のクエリパラメータ

https://localhost:3000/work?day=1024&user_id=3&group_id=4

「?」以降がクエリパラメータで
「キー=値」
複数ある場合は「&」で繋げる

・クエリ文字から値を取得したい場合
コントローラーに処理を記載する必要がある。

# コントローラーで値の取り方
# キーを指定して1個取りたい

value = params[:day] 
#コントローラーでの便利な使い方
def index
  if params[:user_id]
    @user = User.find(params[:user_id])
  else
    # パラメータがないときの処理
  end
end

・パラメータ作成方法

<% link_to 'ユーザー詳細', user_work_path(day: 1024, user_id: 3, group_id: 2) ​%>

【参考記事】
【Ruby on Rails】クエリ文字列でURLからパラメータを取得する方法について解説します
https://www.tairaengineer-note.com/ruby-on-rails-query-string-url/

【Ruby on Rails】クエリパラメータを扱う
https://note.com/matsukoutennis/n/n484cfbf51c1a

URL クエリパラメータの正しい設定方法
https://help.webantenna.info/8821/

Rails APIのURLにクエリパラメータを含める
https://keruuweb.com/rails-api%E3%81%AEurl%E3%81%AB%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%82%92%E5%90%AB%E3%82%81%E3%82%8B

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