편집 : 매우 간단한 오류가 발생하여 더 이상 존재하지 않는 LocalTemplate ID와 연결된 템플릿이 있습니다. 누구나이 문제가 있고 어떻게 든 업데이트 작업에서 다른 모델의 ID를 연결할 수 없다고 생각하면 실수로 상위 개체를 삭제하지 않아야 해당 ID가 더 이상 존재하지 않게됩니다! 극적으로 단순화되었지만 아래 코드는 저에게 효과적이었습니다.Rails NoMethodError 정의되지 않은 메소드 'data'for nil : NilClass (Controller # update)
나는 내 레일 앱에 템플릿 모델이 있습니다. 그것에는 "데이터"라는 메소드가 정의되어 있습니다.
@ 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
컨트롤러 : @template가
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'를 재정의 했습니까? '템플릿'? –
일을 명확히하기 위해 많은 코드를 제거했지만'if @ template.update_attributes (template_params)'후에 @ template.data를 사용해야하는 API 호출을합니다. 나는 그 전화를 보여주지 않을 것이지만 그것이 그것이 갈 것이고 그것이 작동하지 않는 곳이다. – dual88
그 라인은 다음과 같습니다 :'Api.new.update_template (@ template.data)' – dual88