Немного фона. Я пытаюсь предварительно заполнить атрибут моей модели Document при создании. Для этого я использую базовую форму помощника «current_user».ActiveRecord :: AssociationTypeMismatch в DocumentsController
Однако, когда я пытаюсь установить @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 схема (как написано в БД)
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
}
]
Я попытался это раньше, но я получаю undefined метод 'to_i 'для # <Пользователь: 0x00000004171700> –
Вы уверены, что первичный ключ и внешний ключ верны? Кажется странным, что ваш внешний ключ - это просто «id». Обычно это будет нечто вроде «user_id» или «creator_id», в зависимости от того, как настроена ваша БД. –
Я так думаю? Добавлен JSON-представление table_info к исходному вопросу. –