Rails回滚事务

时间:2017-12-30 17:08:04

标签: ruby-on-rails ruby transactions rollback

我的Rails Block出了问题。在我实施评论部分后,我无法再创建帖子了。控制台给我一个回滚事务。所以我做了

bool containsOnlyAllowedSymbols(const char* equation)
{
    bool a;
    while (*equation) {
        if ((*equation < 48 || *equation > 57) && *equation != '+' && *equation != '-' && *equation != '*' && *equation != '/' && *equation != '(' && *equation != ')' && *equation != '[' && *equation != ']' && *equation != '{' && *equation != '}') {
            return false;
        }
        else
            a = true;
        equation++;
    }
    return a;
}

我似乎对用户p = Post.new p.valid? # false p.errors.messages 有一些验证问题。但在我实施评论之前,它确实有效。有人可以帮助我吗?

User.rb

:user=>["must exist"]

Post.rb

class User < ApplicationRecord
  has_many :posts
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable
end

发表-迁移

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy

  validates :title, presence: true, length: {minimum: 5}
  validates :body, presence: true


  has_attached_file :image  #, :styles => { :medium => "300x300>", :thumb => "100x100>" }
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end

Post_controller

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
     create_table :posts do |t|
     t.string :title
     t.text :body

     t.timestamps
     end
   end
 end

1 个答案:

答案 0 :(得分:1)

在创建帖子时,您需要在帖子控制器下的create方法中为该帖子分配用户。你可以尝试这样的事情。

def create
  if current_user
    @post.user_id = current_user.id
  end

  ## More create method stuff
end

默认情况下,在belongs_to关联中,用户需要创建帖子,否则您将无法创建帖子。因为从它的外观来看,你没有任何东西可以在create方法中将用户分配给该帖子。