2
0

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】URLを取得したり操作する方法まとめ

Last updated at Posted at 2019-08-31

こんにちは!
ねこじょーかー(@nekojoker1234)と申します。

Railsの開発をしていると、URLを取得したり、どこから来たかを判断したりしますよね。
そんな人のために、使い方をまとめておきました。

この記事のことを覚えておけば、だいたい何とかなると思います。

表示中のURLを取得する

request.url

遷移元のURLを取得する(どこから来たか)

request.referer

遷移元のURLに指定したパスが含まれているかどうか

/users/editが含まれていれば、trueになります。
また、ボッチ演算子「&」を使用しているのは、referernilになる場合があるためです。
nilに対してメソッドを呼び出すとエラーになる)

request.referer&.include?('/users/edit')

余談ですが、「&」がボッチ演算子と呼ばれているのは、「&」が1人で体育座りをしているように見えることから、そのように名前がついたそうです。

ルートパスかどうか

request.path == "/"

ちなみに、ユーザー一覧のパスかどうかは以下で判断できるので、ルートパス以外にも応用できます。

request.path == "/users"

オブジェクトのURLを取得する

post = Post.find(1)
url = polymorphic_url(post)

これで取得できるのは、「https://〇〇.com/posts/1」です。
オブジェクトを渡すと、そのオブジェクトが表示されるときに使用されるURLが返却されます。

以上です!

あわせて読みたい

HTMLもわからない初心者が、独学で「投稿型SNSサービス」を作ったって本当?【193日間の死闘】

運営している PlayFab 専用ブログ
https://playfab-master.com

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?