Home > Blockchain >  Rails undefined method `' for #<Category:0x0000000114c08658>
Rails undefined method `' for #<Category:0x0000000114c08658>

Time:10-05

I'm struggling with this error and can't find whats happening here, has anyone faced it?

Category model

class Category < ApplicationRecord
  extend FriendlyId
  has_many :products
end

Product model

  belongs_to :category, optional: true
  belongs_to :kit, optional: true

They are associated in product table like this:

t.integer "category_id"

Params

 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"}

Console error

  User Load (2.9ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 204], ["LIMIT", 1]]
  ↳ /Users/enrique/.rvm/gems/ruby-2.7.2/gems/activerecord-5.2.8.1/lib/active_record/log_subscriber.rb:98
Notifying https://notify.bugsnag.com of NoMethodError
  
NoMethodError (undefined method `' for #<Category:0x0000000115997e18>):

Pry

   [1] pry(main)> c = Category.create(id: 4, name: "test")
       (0.1ms)  BEGIN
       (0.1ms)  ROLLBACK
    NoMethodError: undefined method `' for #<Category:0x000000010c18ee78>

Schema

 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

Update Removing Friendly id from Category model seems to fix the issue. I wonder what is happening behind the scenes...

CodePudding user response:

I could replicate the problem, which occurs if you havent finished the setup entirely:

going by the docs:

rails g migration AddSlugToCategories slug:uniq
rails generate friendly_id
rails db:migrate

and then add friendly_id

class Category < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged # <= here
  has_many :products
end

hope this helps ;)

  • Related