Ruby on Rails创建Outfit时出现NoMethodError:undefined method `level'
Ruby on Rails创建Outfit时NoMethodError: undefined method `level'问题解决
在构建Ruby on Rails应用时,创建Outfit资源遇到NoMethodError in OutfitsController#create错误,提示undefined method 'level',但代码中从未定义过level相关内容,使用@outfit.save!也无法解决该问题。
相关代码如下:
控制器代码
def create @user = current_user @outfit = Outfit.new(outfit_params) @outfit.user = current_user if @outfit.save redirect_to outfits_path flash[:notice] = "Outfit created" else flash[:notice] = "Something went wrong, please check the form again" end end private def outfit_params params.require(:outfit).permit(:name, :pet, :price, :color, :style, :size, :description, photos:[]) end def update_outfit_params params.require(:outfit).permit(:name, :pet, :price, :color, :style, :size,:description, photos:[]) end
模型代码
class Outfit < ApplicationRecord belongs_to :user has_many_attached :photos SIZE = ['S', 'M', 'L'] validates_inclusion_of :level, :in => SIZE end
问题根源
错误来自Outfit模型的验证规则写错了字段名:你定义了SIZE数组作为尺码选项,但验证时错误指定了level字段,而你的数据库表和表单参数里都没有level字段,只有size字段,所以当保存Outfit时,Rails尝试调用@outfit.level来验证,就会抛出undefined method 'level'的错误。
解决步骤
- 修正模型的验证规则:把模型中的
validates_inclusion_of :level, :in => SIZE改成validates_inclusion_of :size, :in => SIZE,确保验证的是正确的size字段:
class Outfit < ApplicationRecord belongs_to :user has_many_attached :photos SIZE = ['S', 'M', 'L'] validates_inclusion_of :size, :in => SIZE end
检查数据库表结构:确认Outfit表是否包含
size字段:- 查看对应的迁移文件(位于
db/migrate/目录下),如果没有size字段,生成新的迁移:rails generate migration AddSizeToOutfits size:string - 运行迁移:
rails db:migrate
- 查看对应的迁移文件(位于
重新测试创建功能:启动服务器后再次尝试创建Outfit,错误应该会消失。
内容的提问来源于stack exchange,提问作者Ophe_Ng
相关产品推荐
相关产品推荐

