7

我正在尝试使基本表格起作用并且正在苦苦挣扎,因为我不断收到错误

 undefined method `profiles_index_path' for #<#<Class:0x4fe1ba8>:0x4fccda0>

我已经检查过了,似乎无法弄清楚我哪里出错了。

在我看来(new.html.erb)我有:

 <%= form_for @profile do |f| %>

 <%= f.text_field :name %>
 <%= f.text_field :city %>
 <%= f.text_field :country %>
 <%= f.text_field :about %>

 <%= f.submit "Create Profile" %>

 <% end %>

在我的个人资料控制器中,我有:

class ProfilesController < ApplicationController

def new
  @title = "New Profile"
  @profile = Profiles.new
end

def create
  @user = current_user
  @profile = @user.profiles.new(params[:profile])
  if @profile.save
    redirect_to profile_path, :notice => "Welcome to your new profile!"
  else
    render "profiles#new"
  end
end

def edit
  @user = current_user
  @profile = @user.profiles.find(params[:id])
end

def update
  @title = "Update Profile"

  @user = current_user
  @profile = @user.profiles.find(params[:id])

  if @profile.update_attributes(params[:profile])
    redirect_to profile_path
  else
    render action: "edit" 
  end
end

def index
  @user = current_user
  @profile = @user.profiles.all
  @title = "Profile"
end

end

最后在我的个人资料模型中,我有

class Profiles < ActiveRecord::Base

belongs_to :user

end

人们可以提供的任何帮助真的将不胜感激,因为我很难过。:)

抱歉忘记包含路线:

  controller :profiles do
   get "newprofile" => "profiles#new"
   get "updateprofile" => "profiles#update"
   get "profile" => "profiles#home"
  end

  resources :profiles, :controller => 'profiles'
4

5 回答 5

6

问题确实是您将模型名称复数的方式。不要那样做。它应该是一个Profile,而不是一个Profiles。我有一些工作可以让您使用复数模型名称,但答案是坚持 Rails 约定而不是与框架对抗。将您的模型重命名为Profileurl_for帮助程序将了解如何正确地将新的 Profile 对象转换为/profilesURL。

于 2012-05-07T20:08:24.570 回答
1

如果您运行“rake routes”命令,“profiles_index”是否出现在您的路线中?通常对于模型的索引页面,工作“索引”被省略,因此路线是profiles_path

您的错误可能来自您使用过的视图,profiles_index_path而不是profiles_path

于 2012-05-07T18:14:25.663 回答
1

我认为它失败了,因为您的模型名称没有遵循约定。

所以我认为你的问题主要在于你没有遵循模型名称的约定,这通常是单数的,因为每个实例都代表一个配置文件。我认为 form_for 助手正试图弄清楚如何处理它并因此失败。因此,您有两种选择可以尝试解决。将模型名称重构为单数(我不清楚这将是多么困难)或将 :url 参数传递给 form_for 以便它知道发布到哪里。

<% form_for @profile, :url => path_to_create_action do |f| %>

更多信息在这里:

于 2012-05-07T19:42:35.557 回答
1

我正在使用Rails 5,我遇到了同样的错误,它是使用这个词Media作为我的模型,而 RoR 用作Medium复数所以我在执行时得到了不同的路线rake routes

我所做的修复它是:

  1. 删除我刚刚创建的模型。

    rails d scaffold Media
    
  2. 编辑config/initializers/inflections.rb

    ActiveSupport::Inflector.inflections(:en) do |inflect|
        # Here you can put the singular and plural form you expect
        inflect.irregular 'media', 'medias'
    end
    
  3. 现在再次执行脚手架:

    rails g scaffold Media
    

现在你必须以你期望的方式拥有一切。因为您已经覆盖了Ruby on Rails 中的PluralizationsSingularizations (Inflections)

我希望它有用。

于 2016-09-20T04:44:14.400 回答
0

您是否尝试用以下内容替换您的 form_for 标记?

<%= form_for @profile, :as => :post do |f| %>

看起来它正试图将其视为对“/profile”的 GET 请求。而且,由于它没有找到索引操作,所以它会出错。我认为强迫它做一个 POST 将解决这个问题。

于 2012-05-07T18:14:58.040 回答