[英]Simple_form Error - undefined method `model_name' for ActiveRecord::Relation:Class
[英]form_for undefined method `model_name' for ::ActiveRecord_Relation:Class
我一直在使用form_for呈现问题。 我希望有一个_form.html.erb部分,该部分处理我的问题记录的创建和编辑。 当我走上使用路线时
<%= form_for(@problem) do |f| %>
我收到以下错误:
undefined method `model_name' for Problem::ActiveRecord_Relation:Class
在我的routes.rb中,我有以下内容:
PW::Application.routes.draw do
root to: 'problems#index', via: :get
resources :problems do
member do
post 'up_vote'
post 'down_vote'
end
end
我在问题控制器中也有这个
class ProblemsController < ApplicationController
include Concerns::Votes
def new
@problem = Problem.new
end
def index
@problem = Problem.all
end
def show
@problem = find_problem
end
def create
@problem = current_user.problems.new(problem_params)
@problem.save
redirect_to @problem
end
private
def find_problem
@problem = Problem.find(params[:id])
end
def problem_params
params.require(:problem).permit(:name, :description, :url)
end
end
如果指定以下内容,则可以使其正常工作:
<%= form_for @problem.new, url: {action: "create"} do |f| %>
但是,我觉得如果我然后只为编辑做一个单独的部分,这就是我的重复。 我真的无法弄清楚为什么这不起作用。 可能是我在index.html.erb上呈现表单吗?
任何帮助或指示将不胜感激。
大声笑为什么我没有更早看到这个?
可能是我在index.html.erb上呈现表单吗?
是的,这完全是问题。 原因在这里:
Problem::ActiveRecord_Relation:Class
您将获得一个relation
对象(定义一个集合,而不是单个记录)。 原因是:
#controller
def index
@problem = Problem.all
end
该错误是因为form_for
需要一条记录。 您需要在控制器中使用它,它将起作用:
#controller
def index
@problem = Problem.new
@problems = Problem.all
end
#view
<%= @problems.each do |problem| %>
<%= problem.name %>
<% end %>
<%= form_for @problem do |f| %>
您应该像这样在控制器中定义一个create
方法
def create
@problem = Problem.new
#other logic goes here
end
您的form_for
create
操作应如下所示
<%= form_for @problem, url: {action: "create"} do |f| %>
您可能正在使用@problems
,因为您说表格在索引页中。 如果您这样做,则索引操作代码应类似于
def index
@problems = Problem.all
@problem = Problem.new
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.