The reason for the missing methods is that form_for
in the view are not aware we are nesting. This is fixed by feeding it an array:
form_for([@user, @scaffold])
문제
I am trying to build a Rails app modded from Michael Hartl's Railstutorial. The code is located on GitHub.
I am using the following nested resources:
resources :users do
resources :scaffolds
end
But I am getting the following error:
ActionView::Template::Error (undefined method `scaffolds_path' for #<# <Class:0x007f87848019d0>:0x007f8782651948>):
4:
5: <div class="row">
6: <div class="span6 offset3">
7: <%= form_for(@scaffold) do |f| %>
8: <%= render 'shared/error_messages', object: f.object %>
9: <%= f.text_field :name, placeholder: "Scaffold name" %>
10: <%= f.text_area :description, placeholder: "Description" %>
app/views/scaffolds/new.html.erb:7:in `_app_views_scaffolds_new_html_erb___1119296061714080468_70109999031900'
I am puzzled why it is looking for scaffolds_path
and not user_scaffolds_path
?
The @scaffold
is created in the app/controller/scaffolds_controller.rb:
def new
@scaffold = current_user.scaffolds.build
end
Inspecting the @scaffold
object thus created shows:
'#<Scaffold id: nil, name: nil, description: nil, tax_id: nil, user_id: 36, created_at: nil, updated_at: nil>'
Dumping the methods of @scaffold
don't reveal any scaffolds_path
or user_scaffolds_path
methods which suggest additional problems?
The users model has_many :scaffolds
and the scaffold model belongs_to :user
.
해결책 2
The reason for the missing methods is that form_for
in the view are not aware we are nesting. This is fixed by feeding it an array:
form_for([@user, @scaffold])
다른 팁
It has to do with the form helper. IF you're using nested resources and you never want to perform controller actions on Scaffold
objects directly, then you need to do the following in your form view and model. Something like:
# app/models/user.rb
class User < ActiveRecord::Base
...
accepts_nested_attributes_for :scaffolds
end
...and in the view...
<%= form_for(@user) do |f| %>
...
<%= fields_for @user.scaffold do |scaffold_fields| %>
...this will result in the path for the fields_for
giving you the expected users_scaffolds_path
NOTE that the specifics of how you use the fields_for
helper changes depending on whether it's a has_one
or has_many
relationship and such. The first time through this you may just tear your hair out - so fair warning.
...you want to use Scaffold
objects on their own and as part of a nested route, you can declare the route twice - once for when you want to use it as a nested resource, and once when you want to use it on its own.
# config/routes.rb
resources :users do
resources :scaffolds
end
resources :scaffolds
With this, when you run rake routes
you'll see both users_scaffolds_path
and scaffolds_path
for all the standard actions.