eva*_*vee 3 ruby activerecord ruby-on-rails
我试图将记录添加到一个连接表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)
Run Code Online (Sandbox Code Playgroud)
用户模型
class User < ActiveRecord::Base
...
has_many :user_logs
has_many :user_actions, :through => :user_logs
end
Run Code Online (Sandbox Code Playgroud)
用户操作模型
class UserAction < ActiveRecord::Base
has_many :user_logs
has_many :users, :through => :user_logs
end
Run Code Online (Sandbox Code Playgroud)
用户日志模型
class UserLog < ActiveRecord::Base
belongs_to :user
belongs_to :user_action
end
Run Code Online (Sandbox Code Playgroud)
架构
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
Run Code Online (Sandbox Code Playgroud)
小智 7
您正在尝试将UserAction对象添加到UserLog集合中,这肯定会引发TypeMismatch错误.试试这个:
user = User.first
action = UserAction.first
user.user_actions << action
user.save
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14573 次 |
| 最近记录: |