Reputation:
I am trying to add the username of an author to a post in my blog, in order to later be able to verify that the user attempting to alter the post is the original author of the post. However, it is not working, and is returning the error "Validation failed: User must exist", even though the current user does exist, based on the fact that it is displaying the username of the currently logged in user on the page.
Error log:
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
Application controller (where current_user is declared):
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
Post model:
class Post < ApplicationRecord
has_many :comments
belongs_to :category
belongs_to :user
end
Schema:
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
Error when I do what Vasilisa said:
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)
Upvotes: 1
Views: 84
Reputation: 4640
The Post model belongs_to :user
, in ROR 5 this association validates for presence automatically. That's why you're getting "Validation failed: User must exist". Looks like you want to store post's user as author
in db.
Change your posts table in migration
def change
remove_column :posts, :author, :string
add_reference :posts, :author
end
In the Post model change belongs_to :user
to belongs_to :author, class_name: 'User'
Add to the User model
has_many :posts, foreign_key: :author_id
After it you can just write current_user.posts
in the controller
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Post created."
redirect_to post_path(@post.id)
else
render :new
end
end
And please, read again about associations in Rails
Upvotes: 1