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

Rails中Category模型undefined method错误排查求助

Rails中Category模型触发undefined method '' for #<Category>错误的解决与原因

问题重现

操作Category模型时(包括创建、更新)触发NoMethodError,错误日志显示:

NoMethodError (undefined method `' for #<Category:0x0000000115997e18>)

直接在控制台执行Category.create(id: 4, name: "test")也会触发相同错误,但移除Category模型中的extend FriendlyId后,问题消失。

相关代码与环境信息

Category模型(出错版本)

class Category < ApplicationRecord
  extend FriendlyId
  has_many :products
end

Product模型

class Product < ApplicationRecord
  belongs_to :category, optional: true
  belongs_to :kit, optional: true
end

Categories表结构

create_table "categories", force: :cascade do |t|
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string "name"
  t.integer "order"
  t.string "icon"
  t.boolean "active", default: false
end

更新操作的请求参数

Parameters: {"utf8"=>"✓", "authenticity_token"=>"wXp/J/hZOuyXJwh6PRzKaAmyF94fCBgLVXMyHdJAOhflt5nCalgHOviT7sRd6bCAVYQLn85xMVO9tGe0ozQUDw==", "category"=>{"name"=>"Navidad", "order"=>"1", "icon"=>"ginger-man", "active"=>"1", "product_ids"=>["", "", "2620", "2616"]}, "return_to"=>"http://localhost:3000/administrador/category", "_save"=>"", "model_name"=>"category", "id"=>"84"}

原因解析

这个错误的核心是FriendlyId扩展未完成必要配置。FriendlyId需要通过friendly_id方法指定用于生成友好URL的字段(如name)及使用的策略,仅写extend FriendlyId而未配置字段时,FriendlyId内部逻辑会尝试调用一个空字符串对应的方法,从而触发undefined method ''的异常。

解决方案

方案1:正确配置FriendlyId

在Category模型中补充friendly_id配置,指定slug生成字段和策略:

class Category < ApplicationRecord
  extend FriendlyId
  # 指定用name字段生成slug,使用slugged策略
  friendly_id :name, use: :slugged
  has_many :products
end

首次配置需执行以下命令添加slug字段到数据库:

rails generate friendly_id
rails db:migrate

方案2:移除无用的FriendlyId扩展

如果项目不需要FriendlyId生成友好URL的功能,直接删除extend FriendlyId即可,这也是你之前临时解决问题的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:15:28