form_for [@parent, @child] 导致 Child#new 中未定义的方法`parent_child_path' [英] form_for [@parent, @child] causes undefined method `parent_child_path' in Child#new

查看:31
本文介绍了form_for [@parent, @child] 导致 Child#new 中未定义的方法`parent_child_path'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以一个用户有很多大学(他们就读过),一个大学属于一个用户.我将这些大学称为 College_profile,因为它们是用户个人资料的大学属性.

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

视图同样简单:(views/college_profiles/new.html.erb)

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>

因为我还在学习 Rails,我真的不明白这个错误到底指的是什么.相当多的谷歌搜索并没有给我带来任何运气,或者如果答案就在那里,我根本不知道我在看它.任何帮助将不胜感激!

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!

推荐答案

form_for 的一点是它的 URL 基于您传入的模型.在您的情况下,它是:>

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 会自动查找 user_college_profiles_path 因为您将 User 分配给 @user,并将 current_user.college_profile 分配给 <代码>@college.

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

幸运的是,Rails 提供了一种方法来覆盖表单将在提交时访问的默认 URL:

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| %>

您需要做的就是在您的 routes.rb

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

来源:Ruby on Rails 指南:Rails 表单助手

这篇关于form_for [@parent, @child] 导致 Child#new 中未定义的方法`parent_child_path'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆