Rails 出价回滚交易

Rails rollback transaction for bids

您好,当我尝试从 rails 控制台创建出价时,我收到回滚交易。这些是我的模型:

产品型号

class Product < ApplicationRecord
 belongs_to :user
 belongs_to :category
 has_many :ratings
 has_many :bids

end

出价模型:

class Bid < ApplicationRecord
 belongs_to :products
 belongs_to :user
 
end

用户模型:

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

这是我的架构:

ActiveRecord::Schema.define(version: 20161231124005) do

  create_table "bids", force: :cascade do |t|
    t.integer  "amount"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
    t.integer  "product_id"
    t.index ["product_id"], name: "index_bids_on_product_id"
    t.index ["user_id"], name: "index_bids_on_user_id"
  end

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "products", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.string   "image_url"
    t.integer  "price"
    t.datetime "deadline"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
    t.integer  "category_id"
  end

  create_table "ratings", force: :cascade do |t|
    t.integer  "rating"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
    t.integer  "product_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "username"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["username"], name: "index_users_on_username", unique: true
  end

end

虽然我尝试这样创建:Bid.create(amount: 500, user_id: 1, product_id:6) 由于回滚事务,它没有保存。

提前致谢

您发布的代码并没有真正帮助。您还应该添加日志。 在发布任何日志之前,我会在控制台中尝试 b = Bid.new(amount: 500, user_id: 1, product_id: 6)b.save。之后,执行 b.errors 并查看导致回滚的原因。

编辑:添加 .save.

EEDIT:对于遇到相同问题的任何人,问题是 Bid 模型引用了 Product 错误。 使用 belongs_to 时,模型应该是单数,而不是复数。例如:belongs_to: apple 而不是 belongs_to: apples