Form_for undefined method `model_name 'for :: ActiveRecord_Relation: Class

I'm having problems with form_for rendering. I want to have the _form.html.erb part that deals with both creating and editing my problem record. When I walk the way of use

<%= form_for(@problem) do |f| %>

I get the following error:

undefined method `model_name' for Problem::ActiveRecord_Relation:Class

On my .rb routes, I have the following:

PW::Application.routes.draw do
root to: 'problems#index', via: :get
resources :problems do
member do
  post 'up_vote'
  post 'down_vote'
 end
end

I also have this in task manager

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

I can make it work if I specify the following:

<%= form_for @problem.new, url: {action: "create"} do |f| %>

However, I feel this is repeated if I have to do a separate partial for editing only. I really cannot understand why this does not want to work. Maybe I'm making a form on index.html.erb?

Any help or guidance would be greatly appreciated.

+4
3

LOL, ?

index.html.erb?

, . :

Problem::ActiveRecord_Relation:Class

relation ( , ). :

#controller
def index
   @problem = Problem.all
end

beacuse 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| %>
+10

create, ,

def create
 @problem = Problem.new

 #other logic goes here
end

form_for create :

<%= form_for @problem, url: {action: "create"} do |f| %>
0

, @problems, , . ,

def index
  @problems = Problem.all
  @problem = Problem.new
end
0

Source: https://habr.com/ru/post/1538362/


All Articles