我最近请求帮助重新排序复选框列表,Ruby on Rails: re-order checkbox tag
我找到了一个很好的答案,然后离开并更改了我的代码。由此,
<div class="tech" STYLE="text-align: left;">
<b>Technologies:</b>
<style>
.split { text-align:left; }
</style>
<p><ul>
<% for technol in Technol.all %>
<li class="split">
<%= check_box_tag "project[technol_ids][]", technol.id, @project.technols.include?(technol) %>
<%= technol.tech %>
</li>
<% end %>
</ul>
</p>
对此,
<div class="tech" STYLE="text-align: left;">
<b>Technologies:</b>
<style>
.split { text-align:left; }
</style>
<p><ul>
<% @all_technols.each do |technol| %>
<li class="split">
<%= check_box_tag "project[technol_ids][]", technol.id, @project.technols.include?(technol) %>
<%= technol.tech %>
</li>
<% end %>
</ul>
</p>
项目控制器动作新看起来像这样:
def new
@project = Project.new
@technol = Technol.new(params[:tech])
@all_technols = Technol.order('tech ASC')
tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil?
@project_technol = @project.projecttechnols.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @project }
end
end
我现在注意到,如果用户输入一个新项目,并且在我的代码中出现 a validates_presence_of
orvalidates_format_of
标志,则不会显示错误消息,而是会收到以下错误消息:
NoMethodError in Projects#create
line #256 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #256):
253:
254: <p><ul>
255:
256: <% @all_technols.each do |technol| %>
257:
258:
259:
它一定与重新排序技术有关,但我似乎找不到解决办法。希望有人能看到我哪里出错了。提前致谢。
编辑
def create
@project = Project.new(params[:project])
@project.client = params[:new_client] unless params[:new_client].blank?
@project.role = params[:new_role] unless params[:new_role].blank?
@project.industry = params[:new_industry] unless params[:new_industry].blank?
@project.business_div = params[:new_business_div] unless params[:new_business_div].blank?
if !params[:technols].nil?
params[:technols][:id].each do |tech|
if !tech.empty?
@project_technol = @project.projecttechnols.build(:technol_id => tech)
end
end
end
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end