【问题标题】:Unknown attribute 'user_id' for Comment works locally but not on Heroku - RailsComment 的未知属性“user_id”在本地工作,但在 Heroku 上不起作用 - Rails
【发布时间】:2016-02-08 16:51:50
【问题描述】:

在本地我可以创建评论就好了,但是在 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 并检查实际的“评论”结构,没有 user_id,这怎么可能?

【问题讨论】:

  • 您是否忘记在部署时迁移数据库?
  • 迁移正常。一切都已迁移。

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


【解决方案1】:

也许你忘记了这一点(如果它在本地工作,如你所说)?

heroku run rake db:migrate

【讨论】:

  • 其实不是这个。迁移没问题。
  • heroku restart 做得好吗?对不起坚持。 :)
【解决方案2】:

如果用户拥有评论:(评论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 是一个很好的解决方案。

【讨论】:

  • JWT 似乎没有必要。只需使用current_user
  • 如果你有一个 api 就非常有用
  • 到底是怎么做的有什么问题?我的意思是在普通工作方面?很明显,它从参数中获得了一个用户 ID。
  • @PetrosKyriakou 任何人都可以伪造他们的帐户 - 并充当其他人,甚至是管理员。
  • @penne12 谢谢你的意见,但那是另一回事,请再次查看我的帖子,我发现了一些新的东西谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多