我试图允许用户将项目输入数据库。其中一个字段允许他们为该项目输入多种技术。
这是我的项目控制器,新建和创建操作。
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 %>
项目.rb
class Project < ActiveRecord::Base
attr_accessible :tech
has_many :projecttechnols
has_many :technols, :through => :projecttechnols
end
技术.rb
class Technol < ActiveRecord::Base
attr_accessible :tech
has_many :projecttechnols
has_many :projects, :through => :projecttechnols
end
工程技术.rb
class Projecttechnol < ActiveRecord::Base
attr_accessible :project_id, :technol_id
belongs_to :technol
belongs_to :project
end
目前,我有一个页面,用户可以在其中输入一项新技术。但我想将此选项移至创建新项目页面,他们可以在其中选择现有技术,或输入新技术,或两者兼而有之,他们将与该项目一起保存。
但是,当我尝试保存一个新项目时,我收到了这个错误。
Showing /home/james/Desktop/webapp/app/views/projects/new.html.erb where line #233 raised:
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/>
我是 Rails 新手,还在学习,所以请记住回答。提前致谢。
编辑
改变后
@project.projecttechnols.build(:technol_id => technol)
至
@project_technol = @project.projecttechnols.build(:technol_id => technol)
我现在收到此错误:
NoMethodError in Projects#create
undefined method `map' for nil:NilClass
Extracted source (around line #240):
237: <div class="tech">
238: <%= ab.label "All Tech" %><br/>
239:
240: <%= collection_select(:technols, :id, @all_technols, :id, :tech, {}, {:multiple => true} ) %>
241: </div>
242: <% end %>
编辑 2
@all_technols = 创建操作中的 Technol.all
我现在得到这个错误。
NoMethodError in Projects#show
Showing /home/james/Desktop/webapp/app/views/projects/show.html.erb where line #181 raised:
undefined method `technol' for #<Project:0xb36823c>
Extracted source (around line #181):
178: <h3>Related books</h3>
179:
180: <ul>
181: <% @project.technol.each do |technol| %>
182: <li><%= technol.tech %> <%= link_to "Details", technol_path(technol) %></li>
183: <% end %>
184: </ul>