Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
54
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでGETメソッドのクエリストリングで配列を渡したい時にどうするか

Posted at

考えられるパターン

1. 変数名に[]を付けるパターン

https://example.com/hoge&jobs[]=foo&jobs[]=bar
  • params[:jobs] で配列を取得できる
  • URLが冗長

2. カンマ区切りで渡すパターン

https://example.com/hoge&jobs=foo,bar
  • params[:jobs].split(',') で配列を取得できる
  • URLがスッキリする

結論

Array に to_query メソッドが存在したので、その実行結果に従うと良さそう。

console
pry(main)> ["hoge", "piyo"].to_query("jobs")
=> "jobs%5B%5D=hoge&jobs%5B%5D=piyo"

ということで、Rails Wayに従うと、「 1. 変数名に[]を付けるパターン 」 を採用するのが良さそう。
[] をURLエンコードした %5B%5D を使用する。
最終的なRails Wayに従ったURLの形は下記となる。

https://example.com/hoge&jobs%5B%5D=hoge&jobs%5B%5D=piyo

参考

php - How to pass an array within a query string? - Stack Overflow
http - Passing array of parameters through get in rails - Stack Overflow

54
38
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
54
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?