evanvee
evanvee

Reputation: 315

Rails 4 ActiveRecord::AssociationTypeMismatch

I am trying to add a record to a join table user_logs which joins user_actions and users. However, when I try add an item with the following code I get the error message below. Why am I getting this error? I have included the models and schema below for reference.

2.0.0-p353 :001 > user = User.first
2.0.0-p353 :002 > action = UserAction.first
2.0.0-p353 :003 > user.user_logs
UserLog Load (0.3ms)  SELECT `user_logs`.* FROM `user_logs` WHERE `user_logs`.`user_id` = 1
=> #<ActiveRecord::Associations::CollectionProxy []> 
2.0.0-p353 :004 > user.user_logs << action
(0.3ms)  BEGIN
(0.2ms)  ROLLBACK
ActiveRecord::AssociationTypeMismatch: UserLog(#2156995120) expected, got UserAction(#2177269140)

User Model

class User < ActiveRecord::Base
   ...
   has_many :user_logs
   has_many :user_actions, :through => :user_logs
end

User Actions Model

class UserAction < ActiveRecord::Base
   has_many :user_logs
   has_many :users, :through => :user_logs
end

User Logs Model

class UserLog < ActiveRecord::Base
  belongs_to :user
  belongs_to :user_action
end

Schema

create_table "user_actions", force: true do |t|
  t.string   "action",     limit: 40, default: "", null: false
  t.datetime "created_at"
  t.datetime "updated_at"
end

add_index "user_actions", ["action"], name: "index_user_actions_on_action", unique: true, using: :btree

create_table "user_logs", force: true do |t|
  t.integer  "user_id"
  t.integer  "user_action_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Upvotes: 4

Views: 25406

Answers (1)

shinnc
shinnc

Reputation: 913

You're trying to add UserAction object to UserLog collection which will definitely throw a TypeMismatch error. Try this instead:

user = User.first
action = UserAction.first
user.user_actions << action
user.save

Upvotes: 7

Related Questions