Comment的未知属性'user_id'在本地工作,但在Heroku - Rails上不起作用

时间:2015-11-07 17:13:36

标签: ruby-on-rails ruby ruby-on-rails-4 heroku ruby-on-rails-3.2

本地我可以创建评论就好了但是在heroku上我得到了这个错误

ActiveRecord::UnknownAttributeError (unknown attribute 'user_id' for Comment.):
app[web.1]:   app/controllers/blog/comments_controller.rb:9:in `create' 



  Parameters: {"utf8"=>"✓", "authenticity_token"=>"g83t8MpETbolCJq0vYku4SbnaZAro5ggXUI1PGVFJ18xneGcGCWQPjXHTfgBKBIP2/5WqHjfxf2d12+Pyq4PNA==", "comment"=>{"name"=>"test", "email"=>"tester@kostis.com", "body"=>"teste", "user_id"=>"1", "post_id"=>"1"}, "commit"=>"Create comment"}

这是我的控制器

class Blog::CommentsController < Blog::BaseController

  def new

    @comment = Comment.new
  end

  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      flash[:success] = "Comment successfully created!"
      redirect_to blog_post_url(@comment.post)
    else
      flash[:warning] = "There was an error with your comment. Please scroll down to see the errors."
      @post = @comment.post
      render 'blog/posts/show'
    end
  end

  def edit
    @comment = Comment.find_by(id: params[:id])
  end

  def update
    @comment = Comment.find_by(id: params[:id])
    if @comment.update(comment_params)
      flash[:success] = "Successfully updated..."
      redirect_to blog_post_path(@comment.post)
    else
      render :edit
    end
  end

  private
      def comment_params
        params.require(:comment).permit(:body,:name,:email,:user_id,:post_id)
      end
end

更新:

我的本​​地迁移文件就是这个

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :name
      t.string :email
      t.text :body
      t.boolean :spam, default: false
      t.references :post, index: true, foreign_key: true
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

但是通过在heroku上运行rails c并检查实际的“Comment”结构,没有user_id,这怎么可能?

2 个答案:

答案 0 :(得分:1)

如果用户拥有评论:(评论belongs_to: :user

加载用户:

user = User.find([id])

然后创建评论:

user.comments.new(comment_params)

如果帖子拥有评论:(评论belongs_to: :post

加载用户:

post = Post.find([id])

然后创建评论:

post.comments.new(comment_params)

尽量不让客户说出他们是谁 - 有人可能很容易伪造他们是不同的用户,然后他们说的是谁。 JWT是一个很好的解决方案。

答案 1 :(得分:0)

也许你忘了这个(如果它在本地工作,正如你所说的那样)?

heroku run rake db:migrate