Rails 4 has_one - 总是覆盖第一条记录

Rails 4 has_one - always overwrites first record

起初我认为这是一个验证问题,但后来意识到每次保存一条记录时它只会覆盖第一条记录。

List.rb

belongs_to :user, :foreign_key => "user_id"

在我的模型中我有:

create_table "lists", force: :cascade do |t|
t.text     "pont12"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer  "user_id"
end

User.rb

has_one :list, dependent: :destroy

列表控制器

def new
@list = current_user.build_list
...
def create
@list = current_user.build_list(list_params)
....

在我 "successfully" 在前端创建列表后的日志中:

User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 4]]
List Load (0.1ms)  SELECT  "lists".* FROM "lists" WHERE "lists"."user_id" = ? LIMIT 1  [["user_id", 4]]
(0.3ms)  begin transaction
SQL (0.4ms)  INSERT INTO "lists" ("pont12", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["pont12", "the list..."], ["user_id", 4], ["created_at", "2015-03-06 10:03:45.368204"], ["updated_at", "2015-03-06 10:03:45.368204"]]
(11.1ms)  commit transaction

这刚刚覆盖了第一条记录。

ps:Rails 的新手 ;)

我发现了问题:foreign_key 需要在 has_one 上,而不是在模型中的 belongs_to 行上。