3

I have two models that I would like to join with a many-to-many relationship.

class Klass < ApplicationRecord
    has_and_belongs_to_many :users
end

class User < ApplicationRecord
  has_and_belongs_to_many :klasses
end

I also created a join table for the two tables which looks like this

class CreateKlassesSchoolsJoinTable < ActiveRecord::Migration[6.1]
  def change
    create_table :klasses_users, id: false do |t|
      t.belongs_to :klass
      t.belongs_to :user
    end
  end
end

When I try to create a record with an association like this

u = User.create!()
k = Klass.create!()
u.klasses << k

I get:

Klass Load (0.3ms)  SELECT "klasses".* FROM "klasses" ORDER BY "klasses"."id" ASC LIMIT $1  [["LIMIT", 1]]
  TRANSACTION (0.1ms)  BEGIN
  User::HABTM_Klasses Create (0.6ms)  INSERT INTO "klasses_users" ("klass_id", "user_id") VALUES ($1, $2)  [["klass_id", 76], ["user_id", 732]]
  TRANSACTION (1.9ms)  COMMIT
(Object doesn't support #inspect)

Can somebody please explain to me what the error (Object doesn't support #inspect) means, and what am I doing wrong in trying to create a many-to-many relationship between these two models? Thanks!

  • 1
    I don't see any problems with the HABTM association. Also, the `#<<` completes successfully, as evidenced by the `COMMIT`. So, it's possible this message "(Object doesn't support #inspect)" has nothing to do with your association. – Jared Beck Sep 07 '21 at 21:14
  • Thanks @JaredBeck ! Which syntax can I use to see all of the klasses associated with a user? user.klasses returns (Object doesn't support #inspect). I dont understand what that means if the models are associated. – Marcel Degas Sep 07 '21 at 21:53
  • `user.klasses` will give you all the klasses for that user. `(Object doesn't support #inspect)` is completely unrelated to the code in the question. It could be caused by a gem or anything else in your code and is impossible to diagnose without a stack trace. – max Sep 08 '21 at 05:37
  • Does this answer your question? [(Object doesn't support #inspect)](https://stackoverflow.com/questions/7690697/object-doesnt-support-inspect) – Jared Beck Sep 08 '21 at 16:17
  • No, unfortunately I looked through each of those answers and none of them seem applicable. I am not defining an initialize method in my models, nor any after_initialize methods anywhere. Gems I am using are devise, devise-jwt, and jsonapi-rails. Besides that everything is standard. Strangely enough, if create a User and run user.inspect, I am getting a response so it seems like the #inspect method is working. Also, unfortunately there is no stack trace. Only the returned string (Object doesn't support #inspect) when I run user.klasses – Marcel Degas Sep 08 '21 at 18:48
  • Do you happen to know of any workarounds or other ways that I can get a many-to-many relationship working between Users and Klasses? – Marcel Degas Sep 08 '21 at 18:50

0 Answers0