问题描述:

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

def index

@posts = Post.all

end

def new

@post = Post.new

end

def create

@post = Post.new(params.require(:post).permit(:task))

@post.user = current_user

if @post.save

redirect_to @post, alert:"Post created successfully."

else

redirect_to new_post_path, alert: "Error creating post."

end

end

def show

@post = Post.find(params[:id])

end

end

The user model

class User < ActiveRecord::Base

devise :database_authenticatable, :registerable,

:recoverable, :rememberable, :trackable, :validatable

has_many :posts

end

Post model

class Post < ActiveRecord::Base

validates_presence_of :task

belongs_to :user

end

网友答案:

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)

Post.column_names

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.

I have

@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

相关阅读:
Top