ruby-on-rails - 未知属性 `user_id'

标签 ruby-on-rails devise

我正在尝试将我使用 Devise 创建的用户与帖子相关联。但是每当我尝试创建以用户身份登录的帖子时,我都会收到标题中提到的错误。非常感谢:)

 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 User < ActiveRecord::Base

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

  has_many :posts
end

后模型

class Post < ActiveRecord::Base

validates_presence_of :task
belongs_to :user

end

最佳答案

对于添加用户 id 以固定以下对我有用

rails g migration add_user_to_pin user_id:integer

关于ruby-on-rails - 未知属性 `user_id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718311/

相关文章:

sql - 通过 named_scope 返回对象数组 -- has_many...belongs_to 关联; UNION ALL 查询

ruby-on-rails - Rails 中的推荐引擎

ruby-on-rails - 在 Rails 4 中向模型添加属性

jquery - 经过身份验证的用户从 jQuery 向 Rails API 发出 AJAX 请求

ruby-on-rails - 如何使用设备配置超时?

ruby-on-rails - Devise 注册后立即在 Controller 中执行某些操作

ruby-on-rails - 跨样式表的 SCSS 常量 (Rails)

ruby-on-rails - Ruby(Rails)将属性委托(delegate)给另一个模型的方法?

ruby-on-rails-3 - 设计 - 如果帐户未确认则重定向到页面

ruby-on-rails - 设备登录后提交表单