2
我在这里发布,因为我找不到任何人有这个错误。我使用Rails 4.0.2,当我尝试保存我的形式(它采用了collection_check_box)它给了我这个消息:未定义的方法`名称'为零:NilClass保存
NoMethodError (undefined method `name' for nil:NilClass):
app/controllers/projeto_controller.rb:34:in `block in create'
app/controllers/projeto_controller.rb:33:in `create'
我有点丢在这里,因为我没有任何属性命名为name
。 在这里我的控制器和模型。
class Projeto < ActiveRecord::Base
belongs_to :usuario
has_many :projeto_temas
has_many :temas, through: :projeto_temas
accepts_nested_attributes_for :temas
validates_presence_of :titulo, :orgao_financiador, :periodo_inicio, :periodo_fim
end
class ProjetoController < ApplicationController
# GET /projeto/new
def new
@projeto = Projeto.new
render :layout => 'application_cadastro'
end
# POST /projeto
# POST /projeto.json
def create
@projeto = Projeto.new(projeto_params)
respond_to do |format|
if @projeto.save
format.html { redirect_to @projeto, notice: 'Projeto was successfully created.' }
format.json { render action: 'show', status: :created, location: @projeto }
else
format.html { render action: 'new' }
format.json { render json: @projeto.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /projeto/1
# PATCH/PUT /projeto/1.json
def update
respond_to do |format|
if @projeto.update(projeto_params)
format.html { redirect_to @projeto, notice: 'Projeto was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @projeto.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_projeto
@projeto = Projeto.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def projeto_params
params.require(:projeto).permit(:titulo, :usuario_id, :orgao_financiador, :periodo_inicio, :periodo_fim, :resumo, :temas_ids => [])
end
end
和Temas
模型。
class Temas < ActiveRecord::Base
has_many :relacionamento_temas_pai, class_name: RelacaoTemas, foreign_key: :temas_pai_id
belongs_to :relacionamento_temas_filho, class_name: RelacaoTemas, foreign_key: :temas_filho_id
has_and_belongs_to_many :projeto
accepts_nested_attributes_for :relacionamento_temas_pai
validates :nome, presence: true
end
观点与ckeck_box
<div class="presquisadores-preview-action">
<div class="temas-projetos-checkbox">
<%= f.collection_check_boxes :temas_ids, Temas.all, :id, :nome %>
</div>
</div>
它有哪些是葡萄牙语的名字命名nome
一个属性,所以它应该不会影响任何东西的一部分。
在此先感谢您的帮助,真的迷失了方向,不知道该怎么做。
--edit
所以......大量的研究后,我并没有发现问题。其实我正在研究一些rails文档,并看到activerecord
版本的一些问题,所以我更新到rails 4.2.0,现在问题已经消失。 我仍然不知道是什么原因造成的,但现在我的表单正常保存。 感谢所有帮助的人们
如果不读取所有的代码,'nil:NilClass on save'的undefined method'name'意味着你做了'something.name'。你的意思是做'something.nome'吗?转到第34行projeto_controller.rb并检查拼写。 – binarymason
http://guides.rubyonrails.org/i18n.html它帮助你重写默认参数 –
@ m8ss我在项目中搜索过,没有用'.name'找到任何东西,我甚至删除了所有的宝石和让标准来看看其中一个是否导致这个错误。 – danfaiole