I'm trying to associate my users that I created with Devise to the posts . But I am getting the error mentioned int the title whenever I try to create a post logged in as a user. Thank you very much :)
class PostsController < ApplicationController
@posts = Post.all
@post = Post.new
@post = Post.new(params.require(:post).permit(:task))
@post.user = current_user
redirect_to @post, alert:"Post created successfully."
redirect_to new_post_path, alert: "Error creating post."
@post = Post.find(params[:id])
The user model
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
class Post < ActiveRecord::Base
You probably don't have a
user_id column on your Posts table in your db.
In your create action, try something like:
def create @post = Post.new(params.require(:post).permit(:task)) @post.user_id = current_user.id if @post.save redirect_to @post, alert:"Post created successfully." else redirect_to new_post_path, alert: "Error creating post." end end
and also make sure in your Posts database table that you have an integer field called user_id
I just did this same stuff. Mine works this way for me.
I do have a user_id column in my posts table. I verified by doing this in rails console (rails c)
Which returned all the fields, and user_id was among them.
in my Post model it belongs_to :user, and in my User model it has_many :posts.
In my PostsController though, mine differs from yours.
@post = Post.new(post_params) @post.user_id = current_user.id
Which seems to work just fine. This was also written after I implemented Devise for the user