Reputation: 5677
Can anyone explain me on how the paths
are generated using form_for
?. The below code generates a path article_comments_path.
<%= form_for [@article, @comment] do |f| %>
<% end %>
I mean how does it exactly generate article_comments_path
and not articles_comment_path
Upvotes: 1
Views: 142
Reputation: 44715
It is using polymorphic_path
method to determine the path. It is basicaly a wrpaper around polymorphic_url
: http://apidock.com/rails/v4.0.2/ActionDispatch/Routing/PolymorphicRoutes/polymorphic_url
Update:
polymorphic_path
is using internally method called build_named_route_call
. When it gets an array, it pull the last record out of the array (with pop
) and then iterates over the remaining array, changing all the objects to
Then we are left with the last element. It can be singular or plural, this is resolved in polymorphic_url
method with this case statement:
inflection = if options[:action] && options[:action].to_s == "new"
args.pop
:singular
elsif (record.respond_to?(:persisted?) && !record.persisted?)
args.pop
:plural
elsif record.is_a?(Class)
args.pop
:plural
else
:singular
end
where record is a first element of the array (if array is passed). inlection
var is then passed to build_named_route_call
so it can build correct helper name. As you can see this form will generate different paths depending on whether the first element is already persisted or not.
Upvotes: 2