应用程式回滚交易,我不知道为什么

时间:2019-01-05 13:47:28

标签: sql ruby-on-rails ruby sqlite

我很好奇为什么我的Rails应用程序将事务回滚到DB而没有被要求。

美洲豹日志:

Started POST "/posts" for 127.0.0.1 at 2019-01-05 00:32:32 -0500
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"1AlwhyE0VY87oSyCyjmrzgxinJ7+t1TfoYYEDXvfl0pGd4DKE842KXHroFWgtXeusOgt+ZApHmB+e40qliTPjQ==", "post"=>{"title"=>"test", "category_id"=>"4", "body"=>"test"}, "commit"=>"Create Post"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 12], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:7
(0.2ms) begin transaction
↳ app/controllers/posts_controller.rb:14
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ? [["id", 4], ["LIMIT", 1]]
↳ app/controllers/posts_controller.rb:14
(0.1ms) rollback transaction
↳ app/controllers/posts_controller.rb:14
Redirected to http://localhost:3000/posts
Completed 302 Found in 18ms (ActiveRecord: 0.8ms)

后置控制器:

class PostsController < ApplicationController
  before_action :require_user

  def index
    @posts = Post.all
  end

  def new
    @post = Post.new
    @categories = Category.all
  end

  def create
    @post = Post.new(post_params)
    if @post.save(post_params)
      @post.author = current_user.username
      flash[:success] = "Post created."
      redirect_to post_path(@post.id)
    else
      flash[:danger] = "Post not created. Redirecting to main page....."
    redirect_to posts_path
  end
end

查看:

<%= form_for @post do |f| %>
<%= f.label :title, "Title of Post" %>
<%= f.text_field :title, class: "form-control" %>
<%= f.label :body, "Post Text" %>
<%= f.text_area :body, class: "form-control" %>
<%= f.submit "Create Post", class: "btn btn-info"%>
<% end %>

2 个答案:

答案 0 :(得分:0)

您可能会验证author字段的存在。由于create方法中的设置不正确,因此您已使事务回滚:

class PostsController < ApplicationController

  ...

  def create
    @post = Post.new(post_params)
    if @post.save(post_params)
      @post.author = current_user.username
      flash[:success] = "Post created."
      redirect_to post_path(@post.id)

  ...
end

要在数据库中分配author并将其保存在数据库中,您需要在保存之前分配author

class PostsController < ApplicationController

  ...

  def create
    @post = Post.new(post_params)
    @post.author = current_user.username

    if @post.save(post_params)
      flash[:success] = "Post created."
      redirect_to post_path(@post.id)

  ...
end

答案 1 :(得分:0)

取决于您所使用的Rails的版本,并且如果您使用的是Strong Parameters,则必须在控制器中将参数列入白名单。

文档示例:

private
  # Using a private method to encapsulate the permissible parameters
  # is just a good pattern since you'll be able to reuse the same
  # permit list between create and update. Also, you can specialize
  # this method with per-user checking of permissible attributes.
  def person_params
    params.require(:person).permit(:name, :age)
  end