在 rails 中迁移后无法保存到数据库

save to database does not work after migration in rails

我想用 rails 创建一个待办事项应用程序,我决定添加一个登录功能。我添加了用户 table 和两个迁移:一个是将列“user_id”添加到待办事项 table,另一个是使“user_id”不为空。这意味着为了创建一个待办事项,它必须有一个用户 ID。 创建列:

    class AddColumnOnCreateTodos < ActiveRecord::Migration[6.1]
  def change
    add_column(:todos, :user_id, :integer)
  end
end

更改为不为空:

   class ChangeColumnOnCreateTodos < ActiveRecord::Migration[6.1]
      def change
        change_column_null(:todos, :user_id, false)
      end
    end

现在,一切正常。我可以访问当前登录的用户,并且该列添加了非空约束。但是,我的 todo_controller 中的创建函数不知何故不起作用。每次我想创建一个新的待办事项时,SQL 语句如下:

INSERT INTO "todos" ("title", "description", "created_at", "updated_at") VALUES (?, ?, ?, ?) 

我的 todo_controller 的创建方法如下所示:

 def create
    @todo = Todo.new(todo_params)
    if @todo.save
      redirect_to to_dos_path
    else
      render :new
    end
  end

而 todo_params 是这样的:

private
  def todo_params
    user = Current.user.id
    puts user
    params.require(:todo).permit(:title, :description, user)
  end

它不知何故不知道 user_id 列已添加。我是 rails 的新手,所以我错过了什么?我确实重置了整个数据库,做了回滚,迁移,rake db:reset db:migrate,等等。我不知道为什么它不起作用。

您添加了一个非空约束,但您创建的 Todo 没有用户外键,这就是它没有保存的原因。

您需要通过关联创建 Todo,但您需要在您的用户模型中首先拥有此关联:

has_many :todos

这将允许您通过关联创建待办事项

user = Current.user.id
todo = user.todos.create(todo_params)

关于todo_params中permit方法的另一个说明,permit用于允许您的请求附带的参数用于创建或更新记录,只有permit函数内的属性才会被用于创建你的待办事项。所以在 permit 中添加 user 不会真正改变任何东西,因为这个值最初不存在于请求参数中。

另一个解决方案是将允许的参数与 user_id 合并,因此它可以用于创建待办事项

def todo_params
  user = Current.user.id
  params.require(:todo).permit(:title, :description).merge(user_id: user.id)
end