我的rails应用程序中有两个模型User和Event,但我的事件表中user_id始终为NULL
+----+------------+----------+-------------+---------------------+---------+
| id | date | time | venue | created_at | user_id |
+----+------------+----------+-------------+---------------------+---------+
| 1 | 0011-11-11 | 12:00:00 | ait pune | 2015-09-18 11:16:51 | NULL |
| 2 | 0011-11-11 | 12:00:00 | dighi hills | 2015-09-18 14:29:01 | NULL |
| 3 | 0011-11-11 | 12:00:00 | obh | 2015-09-18 14:32:41 | NULL |
| 4 | 0011-11-11 | 12:00:00 | nbh | 2015-09-18 14:46:40 | NULL |
+----+------------+----------+-------------+---------------------+---------+
以下是我的架构
ActiveRecord::Schema.define(version: 20150918134819) do
create_table "events", force: :cascade do |t|
t.date "date"
t.time "time"
t.string "venue", limit: 255
t.integer "user_id", limit: 4
end
create_table "users", force: :cascade do |t|
t.string "email", limit: 255, default: "", null: false
t.string "encrypted_password", limit: 255, default: "", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
end
用户和事件模型如下所示
class User < ActiveRecord::Base
has_one :event, dependent: :destroy
end
class Event < ActiveRecord::Base
belongs_to :user
end
我不知道我哪里出错了
答案 0 :(得分:0)
class User < ActiveRecord::Base
has_many :events, dependent: :destroy
end
class Event < ActiveRecord::Base
belongs_to :user
end
<强>用法强>
arsen = User.create
arsen.events << Event.create
Event.create(user: arsen)
has_many关联表示与另一个的一对多连接 模型。你经常会在a的“另一面”找到这种关联 belongs_to association。此关联表示每个实例 该模型具有零个或多个另一个模型的实例。例如, 在包含客户和订单的应用程序中,客户模型 可以像这样声明: