You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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'的错误。

解决步骤

  1. 修正模型的验证规则:把模型中的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
  1. 检查数据库表结构:确认Outfit表是否包含size字段:

    • 查看对应的迁移文件(位于db/migrate/目录下),如果没有size字段,生成新的迁移:
      rails generate migration AddSizeToOutfits size:string
      
    • 运行迁移:
      rails db:migrate
      
  2. 重新测试创建功能:启动服务器后再次尝试创建Outfit,错误应该会消失。


内容的提问来源于stack exchange,提问作者Ophe_Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:22:26