2012-09-27 76 views
1

我想讓用戶輸入一個項目到數據庫中。其中一個領域允許他們爲該項目輸入多種技術。Ruby on Rails:未定義的方法`model_name'爲NilClass:類

這是我的項目控制器,新建並創建動作。

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 

這是我的多選技術下拉菜單的新項目視圖。

<%= 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 %> 

目前,我有一個頁面,用戶可以輸入一項新技術。但是我想將這個選項移到創建新項目頁面,在那裏他們可以選擇現有的技術,或者輸入一個新的項目,或者兩者兼而有之,然後他們可以保存這個項目。

編輯:更改到的問題,再加上模型的添加文件

當我嘗試保存一個新的項目不過,我得到這個錯誤。

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 

EDIT2:

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 

回答

1

參考this

變化

@project.projecttechnols.build 

@project.technols.build 

假設你有以下型號declar ations

project.rb

has_many :technols 

technols.rb

belongs_to :project_id 
+0

還不行'未定義的方法technols爲#<項目:0xafcef54>':( – Jazz

+0

你有什麼型號名稱? ?? – Salil

+0

對不起,我沒有保存我的模型。感謝您的幫助。我已經更新了我的問題,因爲我現在正在收到另一個錯誤。現在加載創建頁面,我可以選擇數據庫中的技術,但現在我無法保存項目。 – Jazz

相關問題