【发布时间】:2014-08-28 04:03:43
【问题描述】:
编辑:事实证明我犯了一个非常简单的错误,并且有一个与不再存在的 LocalTemplate id 关联的模板。如果有人遇到此问题并认为他们无法在更新操作中关联另一个模型的 id,请确保您没有意外删除导致该 id 不再存在的父对象! 下面的代码虽然大大简化,但确实对我有用。
我的 rails 应用中有一个模板模型。它定义了一个方法“数据”。
我可以使用@template.data 在创建和显示操作中访问此方法,但是在我的控制器的更新操作中使用相同的@template.data 时,我得到一个无方法错误,因为我没有显示正确的本地模板ID。这一行可以在模型中找到base_data = YAML.load(local_template.data)
我在最初保存新模板时存储了关联的 local_template 的 id,但是如何确保在更新操作中再次引用该 id,以免出现 no method 错误?
这里是模板模型和控制器的简化版本
型号:
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 #can't use it here or I get a no method error时遇到了真正的麻烦,您是否在Template中覆盖了update_attributes? -
我删除了很多代码以试图让事情变得清晰,但在
if @template.update_attributes(template_params)之后我进行了一个需要使用@template.data 的API 调用。我没有显示呼叫,但它会去的地方,它不起作用。 -
在那一行之后是这样的:
Api.new.update_template(@template.data) -
对,但是如果满足
if @template.update_attributes(template_params),就不能为nil。这使得错误(表明它为零)非常混乱。您是否删除了该方法中的其他代码?可能值得更换它,并且可能包括您的堆栈跟踪。它是指argument.data而不是Api.new.update_template中的argument? -
布拉德你说得对,我看的不够近。问题其实出在 Template 模型的 data 方法里面。我将更新代码以反映这一点。
标签: ruby-on-rails ruby controller nomethoderror updatemodel