im在栏杆上使用Ruby遇到此错误。我做了一个名为"样式"的脚手架,该脚手架具有标题和描述(字符串和文本),带有Ruby Gem设计的用户会话以及一个称为类别的型号,我用add_category_id_to_styles
添加了样式。我改变了
def new
@style = Style.new
end
to
def new
@style = current_user.styles.build
end
在样式控制器中,现在为我提供了nil:nillclass的未定义方法"样式"。你们中有人知道为什么给我这个错误吗?
设计为您提供方法#user_signed_in?
,以检查当前用户是否登录。如果是,则可以访问#current_user
。因此,您可以:
def new
@style = user_signed_in? ? current_user.styles.build : Style.new
end
当然,您也可以直接检查current_user.present?
,但我认为#user_signed_in?
可以更好地传达意图。