讓我們跟隨一些代碼下來的兔子洞,開始redirect_to @user
redirect_to
執行與location
集重定向到url_for(@user)
link
def redirect_to(options = {}, response_status = {}) #:doc:
...
self.location = _compute_redirect_to_location(request, options)
...
end
def _compute_redirect_to_location(request, options) #:nodoc:
...
else
url_for(options)
...
end
到目前爲止,這麼好。 redirect_to
在如何確定路徑方面沒有發言權。接下來,我們來看看url_for
。 link
def url_for(options = nil)
...
else
...
builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method)
...
builder.handle_model_call(self, options)
...
end
貌似url_for
負責決定URL應該如何建立的。在這種情況下,它被髮送到HelperMethodBuilder。 link
def handle_model_call(target, model)
method, args = handle_model model
target.send(method, *args)
end
def handle_model(record)
...
named_route = if model.persisted?
...
get_method_for_string model.model_name.singular_route_key
...
[named_route, args]
end
def get_method_for_string(str)
"#{prefix}#{str}_#{suffix}"
end
我們走了。 handle_model
獲取(持續)記錄的model_name
,它返回ActiveModel::Name
對象,並從中獲取singular_route_key
。
pry(main)> User.first.model_name.singular_route_key
=> "user"
get_method_for_string
使用singular_route_key
完成輔助方法調用。我將離開邏輯推導"prefix"
/"suffix"
作爲學術練習,但它應該返回"user_path"
。
所以,要回答這個問題,單數形式被編碼到ActiveModel :: Name和HelperMethodBuilder中。希望有所幫助!
和vualá!謝謝,非常感謝。 – craig