编辑:事实证明我犯了一个非常简单的错误,并且有一个与LocalTemplate ID不再存在关联的模板。如果任何人有这个问题,并认为他们以某种方式无法将他们的更新操作中的其他模型的id关联,请确保您没有意外删除导致该ID不再存在的父对象! 下面的代码虽然大大简化,但对我来说却很有用。Rails NoMethodError未定义的方法'数据'为零:NilClass(控制器#更新)
我在我的Rails应用程序中有模板模型。它有一个在其中定义的“数据”方法。
我可以通过@ template.data在创建和显示操作中访问此方法,但是当在我的控制器的更新操作中使用相同的@ template.data时,我得到一个无方法错误,因为我没有显示正确的本地模板ID。这条线可以在它读取的模型中找到base_data = YAML.load(local_template.data)
当初始保存新模板时,我存储了一个关联的local_template的id,但是如何确保我在更新操作中再次引用该id,所以我不得到一个没有方法的错误?
这里是模板模型和控制器的简化版本
型号:
class Template < ActiveRecord::Base
def data
base_data = YAML.load(local_template.data)
# couldn't pass the correct LocalTemplate here because
# the local_template_id I had in my Template model no
# longer existed. Changing the id to a LocalTemplate
# that did exist fixed the issue.
end
end
控制器:
class TemplatesController < ApplicationController
def index
@business = Business.find(params[:business_id])
@templates = @business.templates.all
end
def new
@business = Business.find(params[:business_id])
@local_templates = LocalTemplate.all
@template = @business.templates.build
end
def create
@business = Business.find(params[:business_id])
@local_templates = LocalTemplate.all
@template = @business.templates.build(template_params)
if @template.save
@template.data #works fine here
redirect_to business_url(@template.business_id)
else
render 'new'
end
end
def show
@business = Business.find(params[:business_id])
@template = @business.templates.find(params[:id])
@template.data #works fine here too
end
def edit
@business = Business.find(params[:business_id])
@local_templates = LocalTemplate.all
@template = @business.templates.find(params[:id])
end
def update
@business = Business.find(params[:business_id])
@template = @business.templates.find(params[:id])
if @template.update_attributes!(pass_template_params)
Api.new.update_template(@template.data.to_json) #this is where I had a problem
redirect_to business_url(@template.business_id)
else
render 'edit'
end
end
end
我真的有麻烦协调'@ template.update_attributes(template_params)'与'@template.data#不能在这里使用它或我得到一个没有方法错误'你是否覆盖'update_attributes' in 'Template'? – 2014-08-28 04:18:51
为了让事情清楚,我删除了很多代码,但在'if @ template.update_attributes(template_params)'之后,我做了一个需要使用@ template.data的API调用。我没有显示电话,但这是它的去向,它不起作用。 – dual88 2014-08-28 04:21:41
之后,该行类似于:'Api.new.update_template(@ template.data)' – dual88 2014-08-28 04:24:26