问题
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.
EDIT: Change to question, plus adding of model files
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
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:
Ref this
Change
@project.projecttechnols.build
To
@project.technols.build
Assumption you have following model declarations
project.rb
has_many :technols
technols.rb
belongs_to :project_id
来源:https://stackoverflow.com/questions/12618834/ruby-on-rails-undefined-method-model-name-for-nilclassclass