通过关联设置has-one

时间:2016-12-01 19:42:49

标签: ruby-on-rails devise associations

我努力将cart对象与我的carts_controller.rb中的Devise current_user绑定:

class CartsController < ApplicationController
  def show
    @cart = Cart.find_or_create_by(user_id: current_user.id)
    @products = @cart.products
  end
end

导致此类错误:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column carts.user_id does not exist
LINE 1: SELECT  "carts".* FROM "carts" WHERE "carts"."user_id" = $1 ...
                                             ^
: SELECT  "carts".* FROM "carts" WHERE "carts"."user_id" = $1 LIMIT $2):

这是可预测的结果,因为我的购物车模型:

class Cart < ApplicationRecord
  belongs_to(:account, optional: true)
  has_and_belongs_to_many(:products)
end

通过一个帐户与用户建立关联:

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_one(:cart, through: :account)
  has_one(:account)
end

那是我的schema.rb:

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

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "accounts", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
    t.float    "balance"
    t.index ["user_id"], name: "index_accounts_on_user_id", using: :btree
  end

  create_table "carts", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "account_id"
    t.index ["account_id"], name: "index_carts_on_account_id", using:      :btree
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.integer  "age"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "email"
    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.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
  end

  add_foreign_key "accounts", "users"
  add_foreign_key "carts", "accounts"
 end

我可以通过将引用的user_id字段添加到我的购物车表中来引用current_user,还是通过相应的帐户来完成?

1 个答案:

答案 0 :(得分:1)

您需要将user_id添加到Cart中的购物车和关联:

belongs_to :user

然后你在控制器中尝试做的事情应该有效。