2014-07-12 58 views
3

我试图将我创建的用户与Devise关联到帖子。但是,当我尝试创建以用户身份登录的帖子时,我得到了标题中提到的错误。非常感谢你:)未知属性`user_id'

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 

class Post < ActiveRecord::Base 

validates_presence_of :task 
belongs_to :user 

end 

回答

2

你可能没有你的帖子表user_id列在你的数据库用户模型

class User < ActiveRecord::Base 

    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :posts 
end 

Post模型。

0

在你创建的行动,你可以试试:

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 

,并且确保在你的帖子的数据库表,你有一个整数字段名为USER_ID

0

我只是做了这同样的东西。我的工作方式是这样的。

我的帖子表中有一个user_id列。我通过在轨道控制台(导轨c)中执行此操作来验证

Post.column_names 

哪个返回了所有字段,并且user_id就在其中。

在我的Post模型中,belongs_to:user,在我的用户模型中has_many:posts。

虽然在我的PostsController中,我的不同于你的。

@post = Post.new(post_params) 
@post.user_id = current_user.id 

这似乎工作得很好。这也是我写的制定实施后,为用户

2

为了增加用户ID引脚为我下面的工作

rails g migration add_user_to_pin user_id:integer
0

凝视的是schema.rb表中可以看出 user_id列。如果没有USER_ID你需要添加一个迁移列使用以下命令来添加USER_ID

rails generate migration add_user_id_to_posts user_id: integer 

使用此命令20171220171727_add_user_id_to_posts.rb将创建一个迁移文件名。对你而言,时间戳20141220171727将有所不同。在迁移文件,你会看到你有下面的代码:

class AddUserIdToPosts < ActiveRecord::Migration 
    def change 
    add_column :posts, 'user_id', :integer 
    end 
end 

如果迁移看起来像上面然后运行:

rake db:migrate 

应用迁移。现在重新启动服务器,看看你的代码是否有效。

1

其实,当你想要添加对应于您HAVO创建使用迁移具有关联关系的指标,在​​这种情况下:

rails g migration AddUserIdToPin user:references 

Rails会立即知道要包含索引到第二表使用用户标识唯一,主键,键。

希望这有助于!