Я пытаюсь добавить имя пользователя автора к сообщению в моем блоге, чтобы позже иметь возможность проверить, что пользователь, пытающийся изменить сообщение, является первоначальным автором сообщения. Однако он не работает и возвращает ошибку «Проверка не удалась: пользователь должен существовать», даже если текущий пользователь существует, на основании того, что на странице отображается имя пользователя, вошедшего в систему.
Журнал ошибок:
Validation failed: User must exist
@post = Post.new(post_params)
@post[:author] = current_user.username
->> if @post.save!
flash[:success] = "Post created."
redirect_to post_path(@post.id)
else
Контроллер приложения (где объявлен current_user):
class ApplicationController < ActionController::Base
helper_method :current_user
helper_method :require_user
def current_user
return unless session[:user_id]
current_user ||= User.find(session[:user_id])
end
def require_user
redirect_to '/login' unless current_user
end
end
Почтовая модель:
class Post < ApplicationRecord
has_many :comments
belongs_to :category
belongs_to :user
end
Схема:
create_table "posts", force: :cascade do |t|
t.string "title"
t.integer "category_id"
t.string "author"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Ошибка, когда я делаю то, что сказал Василиса:
ActiveRecord::AssociationTypeMismatch (User(#47015106648260) expected, got "test" which is an instance of String(#47015080074780)):
def create
@post = current_user.posts.build(post_params)
==> @post.author = current_user.username
if @post.save
flash[:success] = "Post created."
redirect_to post_path(@post.id)