我正在尝试向连接表user_logs
添加一条记录,该连接表连接了user_actions
和users
。但是,当我尝试使用以下代码添加项目时,会收到下面的错误消息。为什么会出现这个错误?为参考,我已经包含了模型和模式如下。
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)
用户模型
class User < ActiveRecord::Base
...
has_many :user_logs
has_many :user_actions, :through => :user_logs
end
用户操作模型
class UserAction < ActiveRecord::Base
has_many :user_logs
has_many :users, :through => :user_logs
end
用户日志模型
class UserLog < ActiveRecord::Base
belongs_to :user
belongs_to :user_action
end
架构
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
config/environments/test.rb
中将cache_classes
设置为true
:https://dev59.com/CG025IYBdhLWcg3whWdm。但这并没有解决问题。 - evanvee