【发布时间】:2021-02-28 22:48:00
【问题描述】:
错误:nil:NilClass (NoMethodError) 的未定义方法 `model_name'
我在尝试渲染下面的 haml 时收到此错误:
%section#banner
.row
.medium-12.columns
%h2 Add Testimonial
= simple_form_for(@testimonial) do |f|
.row
.large-6.columns
= f.input :text, as: :text,
placeholder: 'Use this space to write a testimonial about the event(s) you participated.'
.row
.large-6.columns
%p.description
= sanitize('Any testimonial along with your name and profile picture might be used for the promotion of codebar (website, prospectus, etc).')
.row
.large-12.columns.text-right
= f.submit 'Submit testimonial', class: 'button'
控制器如下:
class TestimonialsController < ApplicationController
before_action :authenticate_member!
def get_testimonial
testimonial = Testimonial.where(member_id: testimonial_member_id)
invitations = current_user.workshop_invitations.accepted_or_attended
if invitations.any? and testimonial.blank?
render 'new'
else
render 'show'
end
end
def show
@testimonial = Testimonial.find(testimonial_member_id)
end
def new
@testimonial = Testimonial.new
end
def create
@testimonial = Testimonial.new(testimonial_params)
@testimonial.member_id = current_user
@testimonial.public = false
if @testimonial.save
redirect_to @testimonial
else
render 'new'
end
end
private
def testimonial_params
params.require(:testimonial).permit(:text)
end
def testimonial_member_id
params[current_user]
end
end
有人可以帮我看看为什么返回 nil 吗?如果变量相同,我将传递新函数?
【问题讨论】:
-
上面的代码都没有提到
model_name。错误消息究竟说了什么?它应该包括一个堆栈跟踪,它准确地显示了哪一行代码引用了model_name。 -
不过,调试它的方法是:查看调用了哪个变量
model_name。然后查看该变量的设置位置。然后尝试了解变量设置中是否出现问题,或者您可能只需要优雅地处理nil的情况。 -
但是,我还要指出您的方法:
TestimonialsController#testimonial_member_id非常狡猾。也许应该是params[:id]???
标签: ruby-on-rails ruby