LoginSignup
2
2

More than 5 years have passed since last update.

url_helper で id とかが勝手に補完される件

Last updated at Posted at 2017-11-08

例えば routes.rb で

resources :entries

と定義されていて、 /entries/3 にアクセスしたとする。

app/views/entries/show.html.erb 内に edit_entry_path とかを書く場合、通常は

<%= link_to 'edit', edit_entry_path(@entry.id) %>

とか

<%= link_to 'edit', edit_entry_path(params[:id]) %>

とか書くと思うんだが、実は id を省略して、

<%= link_to 'edit', edit_entry_path %>

と書くことが出来、この場合 id: 3 が補完される。

調べた限りこの書き方はどこにもドキュメントされていないのでおそらく推奨はされていないが、とにかくこれは動く。

具体的に、何がどのように補完されるのかコードを追ってみたところ、

def url_options
      @_url_options ||= {
        host: request.host,
        port: request.optional_port,
        protocol: request.protocol,
        _recall: request.path_parameters
      }.merge!(super).freeze

というコードがあり、ここで :_recall に渡されている request.path_parameters が url_helper の足りない部分を補完する挙動となっている。

view の spec を書くと「id 指定がないよ」とエラーになる。補完すべき id がわからないので当然とも言える。

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