一点背景。我正在尝试在创建时预填充我的 Document 模型的属性。为了做到这一点,我使用了一种基本形式的“current_user”助手。
但是,当我尝试设置时@document.creator = current_user.id
出现ActiveRecord::AssociationTypeMismatch ... User expected, got Fixnum
错误。
我承认我不知道为什么。有人能够澄清究竟是什么不正确吗?
相关的模型和控制器是:
class User < ActiveRecord::Base
include Authority::UserAbilities
attr_accessible :email, :name
has_many :authorizations
end
和
class Document < ActiveRecord::Base
has_one :creator, class_name: "User", foreign_key: "id", primary_key: "creator"
attr_accessible :document_subject, document_keywords
def as_json(options={})
{
:document_subject => document_subject,
:document_keywords => document_keywords,
}
end
end
和
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
和
class DocumentsController < ApplicationController
def create
@document = Document.new(params[:document])
@document.creator = current_user.id
@document.save
respond_to do |format|
if @document.save
format.json { render json: @document, status: :created, location: @document }
else
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
和数据库模式(写入数据库)
PRAGMA table_info(users);
[,
{
"cid": 0,
"name": "id",
"type": "INTEGER",
"notnull": 1,
"dflt_value": null,
"pk": 1
},
{
"cid": 1,
"name": "name",
"type": "varchar(255)",
"notnull": 0,
"dflt_value": null,
"pk": 0
},
{
"cid": 2,
"name": "email",
"type": "varchar(255)",
"notnull": 0,
"dflt_value": null,
"pk": 0
},
{
"cid": 3,
"name": "created_at",
"type": "datetime",
"notnull": 1,
"dflt_value": null,
"pk": 0
},
{
"cid": 4,
"name": "updated_at",
"type": "datetime",
"notnull": 1,
"dflt_value": null,
"pk": 0
},
{
"cid": 5,
"name": "active",
"type": "boolean",
"notnull": 1,
"dflt_value": 'f',
"pk": 0
}
]
PRAGMA table_info(Documents);
[,
{
"cid": 0,
"name": "id",
"type": "INTEGER",
"notnull": 1,
"dflt_value": null,
"pk": 1
},
{
"cid": 1,
"name": "created_at",
"type": "datetime",
"notnull": 1,
"dflt_value": null,
"pk": 0
},
{
"cid": 2,
"name": "updated_at",
"type": "datetime",
"notnull": 1,
"dflt_value": null,
"pk": 0
},
{
"cid": 3,
"name": "creator",
"type": "integer",
"notnull": 0,
"dflt_value": null,
"pk": 0
},
{
"cid": 4,
"name": "document_subject",
"type": "varchar(255)",
"notnull": 0,
"dflt_value": null,
"pk": 0
},
{
"cid": 5,
"name": "document_keywords",
"type": "varchar(255)",
"notnull": 0,
"dflt_value": null,
"pk": 0
}
]