【问题标题】:Ruby on Rails Form_for errorRuby on Rails Form_for 错误
【发布时间】:2012-12-15 10:55:35
【问题描述】:

我正在使用 Ruby on Rails 作为学校项目制作游戏,但现在我遇到了这个错误:

# 的未定义方法 `storylines_index_path'

我正在制作一个页面,我希望在其中有一个表单来添加故事情节,所以我需要一个包含一些字段的表单。我想使用 form_for 方法。但是添加时出现此错误

这是我的代码:

views/new.html.erb

<% provide(:title, 'Overzicht Storylines') %> 
<h1>Voeg nieuwe storyline toe</h1>
<%= form_for(@storyline) do |f| %>
  <%= render 'shared/error_messages' %>

  <%= f.label :title %>
  <%= f.text_field :title%>

  <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>

<% end %>

storylines_controller.rb

class StorylinesController < ApplicationController   def index
  @storylines = Storylines.find(:all)   end

  def show
    @storyline = Storylines.find(params[:id])   
  end

  def new
    @storyline = Storylines.new   end end

故事线.rb

class Storylines < ActiveRecord::Base   
  attr_accessible :title, :text
end

routes.rb

StoryLine::Application.routes.draw do   
  get "users/new"   
  get "storylines/new"

  resources :users
  resources :storylines
  resources :sessions, only: [:new, :create, :destroy]

  match '/signup',  to: 'users#new'
  match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete

  root to: 'static_pages#home'

  match '/help',    to: 'static_pages#help'
  match '/contact', to: 'static_pages#contact'
  match '/about', to: 'static_pages#contact'
  match '/home', to: 'static_pages#home'

end

【问题讨论】:

  • 通常与路由和/或传递给form_for的对象有关。请将您的routes.rb 和form_for 的行发布到new.html.erb 中好吗?
  • 我已经添加了 routes.rb

标签: ruby-on-rails ruby form-for


【解决方案1】:

Rails 约定要求您以单数形式命名模型,即 Storyline 而不是 Storylines。在类定义中重命名模型名称,控制器应该可以解决这个问题。

【讨论】:

    【解决方案2】:

    当你这样做时

    form_for(@storyline)
    

    它将尝试查找 storylines_index_path,以便在您的数据库中创建 Storyline 对象。

    所以你需要在文件 config/routes.rb 上定义路由,如果你已经定义了应该定义路由的 resources :storylines,如果你不这样做'不想创建 REST 资源,可以创建自己的路由

    match 'storylines/create', to: 'storylines#create', as: :storylines_create
    

    然后在视图上

    我建议阅读 Rails Routing Guide,因为它更好地解释了所有与 Rails 上的路由相关的内容

    【讨论】:

    • 好的,我同意 Ahmad Sherif 的观点,将 storylines.rb 重命名为 storyline.rb 并将 Storylines 类重命名为 Storyline。或者只是创建一个名为 storylines_index_path 的路线指向 Storylines#index (非常糟糕的做法,但它会起作用)
    • 很好,我将感谢您对这项工作投了赞成票,它建立了我的声誉并帮助我获得了更好的合同;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多