undefined method `model_name' for Project:Class
Asked Answered
B

4

15

I've looked through all the related questions but nothing's new for me here.

I have a Project controller with "new" action

class ProjectsController < ApplicationController
  def new
    @newproject = Project.new
  end
end

Project is a simple class, not active record:

class Project
  attr_accessor :name, :description
  def initialize
    @name = ""
    @description = ""
  end
end

I get the error "undefined method `model_name' for Project:Class"

This is an erb file sample:

<%= form_tag(@newproject)  do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :description %><br />
<% end %>
Bichloride answered 30/5, 2012 at 20:25 Comment(0)
A
37

if Project is not an active record subclass, you need these and you can use form_for

class Project
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  def persisted?
    false
  end
  ...
end

view:

<%= form_for(@newproject)  do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :description %><br />
<% end %>
Airdry answered 30/5, 2012 at 21:16 Comment(3)
Viktor, thanks a lot! It helped me. I just stuck on this. Perhaps, this is not the best way to create temporary instance to give out, so that user could create a real active record Project.Bichloride
Indeed, if you ever persist Project, do not use this, use class Project < ActiveRecord::Base but do not override initialize.Bunny
Thanks, great help.@ViktorTrón any pointers how to get more familiar with knowing Rails to extent that you can debug this issue?Weekley
M
3
class Project < ActiveRecord::Base
Muzz answered 30/5, 2012 at 20:29 Comment(5)
In this case I get "Could not find table 'projects'"Bichloride
I just want to create a temp Project instance so that a user at client side could edit new parameters to create a valid Project instance on the server sideBichloride
oh in that case, just use the ActiveRecord persisted class's new object in the form. It is temporary, since you don't save it. If your class is never persisted, see my response.Bunny
If you don't want a a actual database behind your class, but still want to use it in a form, you need to check out this rails cast: railscasts.com/episodes/219-active-modelMuzz
Viktor, good point, temporary Project class now seems to me redundant here. That is temporary active record Project looks like the better solution here.Bichloride
S
3

just for the record - here is the Railscast for that issue:

http://railscasts.com/episodes/219-active-model

Sternson answered 9/1, 2013 at 23:26 Comment(0)
V
1

I had a similar issue because my class wasn't using ActiveRecord; adding the following to my class solved it: include ActiveModel::Model

Vesicate answered 17/2, 2021 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.