本文介绍了Ruby on Rails:NilClass:Class的未定义方法"model_name"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户将项目输入数据库.其中一个字段允许他们为该项目输入多种技术.

I am trying to allow a user to enter a project into a database. One of the fields allows them to enter multiple technologies for that project.

这是我的项目负责人,新建并创建操作.

Here is my project controller, new and create action.

def new
    @project = Project.new

@all_technols = Technol.all

@project_technol = @project.projecttechnols.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @project }
    end
  end


def create

    @project = Project.new(params[:project])

params[:technols][:id].each do |technol|

if !technol.empty?

    @project.projecttechnols.build(:technol_id => technol)
end
end

end

这是我针对多选技术下拉菜单的新项目视图.

Here is my new project view for the multi select technology dropdown.

<%= fields_for(@project_technol) do |ab| %>

<div class="tech">
<%= ab.label "All Tech" %><br/>

<%= collection_select(:technols, :id, @all_technols, :id, :tech, {}, {:multiple => true} ) %>
</div>
<% end %>

目前,我有一个页面,用户可以在其中输入新技术.但是我想将此选项移至创建新项目"页面,他们可以在其中选择现有技术,或输入新技术,或同时进行两项,然后它们将与该项目一起保存.

At the moment, I have a page where the user can enter a new technology. But I want to move this option to the create new project page, where they can either select existing technologies, or enter a new one, or do both, and they would save with that project.

更改为问题,并添加模型文件

但是,当我尝试保存新项目时,出现此错误.

When I try to save a new project however, I am getting this error.

undefined method `model_name' for NilClass:Class

Extracted source (around line #233):

233: <%= fields_for(@project_technol) do |ab| %>
234:
235: <div class="tech">
236: <%= ab.label "All Tech" %><br/>

project.rb

class Project < ActiveRecord::Base

  attr_accessible :tech


  has_many :projecttechnols
  has_many :technols, :through => :projecttechnols
end

technol.rb

class Technol < ActiveRecord::Base
  attr_accessible :tech

has_many :projecttechnols
has_many :projects, :through => :projecttechnols
end

projecttechnol.rb

class Projecttechnol < ActiveRecord::Base
  attr_accessible :project_id, :technol_id

belongs_to :technol
belongs_to :project
end

def new
    @project = Project.new

@all_technols = Technol.all

#@project_technol = @project.projecttechnols.build


@project_technol = Projecttechnol.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @project }
    end
  end

推荐答案

参考

更改

@project.projecttechnols.build

收件人

@project.technols.build

假设您有以下模型声明

project.rb

project.rb

has_many :technols

technols.rb

technols.rb

belongs_to :project_id

这篇关于Ruby on Rails:NilClass:Class的未定义方法"model_name"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:39