Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

ruby on rails - form_for [@parent, @child] causes undefined method `parent_child_path' in Child#new

So a user has many colleges (that they have attended), and a college belongs to a user. I call these colleges, college_profile as they are the college attribute of a user's profile.

I am running into the problem when trying to generate a new college. My controller for the college at the moment is very simple:

def new
  @user = User.find(params[:id])
  @college = current_user.college_profile.build if signed_in?
end

And the view equally as simple: (views/college_profiles/new.html.erb)

<%= form_for [@user, @college] do |f| %>
   <%= render 'shared/error_messages', object: f.object %>
   <%= f.label :name %>
 <% end %>

And yet, for some reason I get the following error:

NoMethodError in College_profiles#new

Showing .../app/views/college_profiles/new.html.erb where line #4 raised:

undefined method `user_college_profiles_path' for #<#<Class:0x5bf1b68>:0x673aef8>

As I am still learning Rails, I really don't even understand what this error is exactly referring to. A fair amount of Google-ing has given me no luck, or if the answer is out there I simply don't know enough to realize I was looking at it. Any help would be greatly appreciated!

If it is relevant, seeing as we're talking about paths, here's an excerpt from my routes file:

resources :users, :only => [:index, :new, :create, :destroy, :update, :edit] do
  resources :college_profiles, :only => [:new, :create]
end

If any more info is needed, just let me know. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The thing about form_for is that its URL is based on the model that you passed in. In your case, it's:

<%= form_for [@user, @college] do |f| %>

Rails automatically looks for user_college_profiles_path because you assigned User to @user, and current_user.college_profile to @college.

Fortunately, Rails provides a way to override the default URL the form will go to on submit:

<%= form_for([@user, @college], :url => your_custom_route_path) do |f| %>

All you need to do is create your_custom_route in your routes.rb

Source: Ruby on Rails Guides: Rails Form Helpers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...