一点背景知识。我试图在创建时预先填充我的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
和DB模式(写入DB)
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
}
]
答案 0 :(得分:1)
期待Active Record对象本身而不是ID。您只需要执行@document.creator = current_user
。
答案 1 :(得分:0)
Beerlington的回复按照描述进行,但仍然不是我想要达到的理想解决方案。
我最终改变了策略:我没有在文档模型中添加创建者字段,而是使用{}创建文档时使用rolify角色。
@document.save
current_user.add_role :creator, @document