ruby on rails - How to handle nested resources/routes correctly? -
i trying build rails app modded michael hartl's railstutorial. code located on github.
i using following nested resources:
resources :users resources :scaffolds end but getting following error:
actionview::template::error (undefined method `scaffolds_path' #<# <class:0x007f87848019d0>:0x007f8782651948>): 4: 5: <div class="row"> 6: <div class="span6 offset3"> 7: <%= form_for(@scaffold) |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 puzzled why looking scaffolds_path , not user_scaffolds_path?
the @scaffold created in app/controller/scaffolds_controller.rb:
def new @scaffold = current_user.scaffolds.build end inspecting @scaffold object created shows:
'#<scaffold id: nil, name: nil, description: nil, tax_id: nil, user_id: 36, created_at: nil, updated_at: nil>' dumping methods of @scaffold don't reveal scaffolds_path or user_scaffolds_path methods suggest additional problems?
the users model has_many :scaffolds , scaffold model belongs_to :user.
it has form helper. if you're using nested resources , never want perform controller actions on scaffold objects directly, need following in form view , model. like:
# app/models/user.rb class user < activerecord::base ... accepts_nested_attributes_for :scaffolds end ...and in view...
<%= form_for(@user) |f| %> ... <%= fields_for @user.scaffold |scaffold_fields| %> ...this result in path fields_for giving expected users_scaffolds_path
note specifics of how use fields_for helper changes depending on whether it's has_one or has_many relationship , such. first time through may tear hair out - fair warning.
if, on other hand...
...you want use scaffold objects on own and part of nested route, can declare route twice - once when want use nested resource, , once when want use on own.
# config/routes.rb resources :users resources :scaffolds end resources :scaffolds with this, when run rake routes you'll see both users_scaffolds_path , scaffolds_path standard actions.
Comments
Post a Comment