user1 = User.create (login: "serge")
    (0.2ms) begin transaction
   SQL (1.2ms) INSERT INTO "users" ("login", "created_at", "updated_at") VALUES (?,?,?) [["Login", "serge"], ["created_at", 2017-02 -12 4:12:24 UTC], ["updated_at", 2017-02-12 16:12:24 UTC]]
    (180.3ms) commit transaction
  => # 
 2.3.3: 005> cart1 = Cart.create
    (0.1ms) begin transaction
    (0.1ms) rollback transaction
  => # 
 2.3.3: 006> cart1 = Cart.create!
    (0.1ms) begin transaction
    (0.1ms) rollback transaction
 ActiveRecord :: RecordInvalid: Validation failed: User must exist 
class CreateCartsItems < ActiveRecord::Migration[5.0] def change create_table :carts_items, id: false do |t| t.references :cart t.references :item end add_index :carts_items, [:item_id, :cart_id] add_index :carts_items, [:cart_id, :item_id] end def self.down drop_table :carts_items end end class Cart < ApplicationRecord belongs_to :user has_and_belongs_to_many :items # validates :user # validates :user_id end class Item < ApplicationRecord validates :name, :description, presence: true validates :price, numericality: { greater_than: 0, allow_nil: true } has_and_belongs_to_many :carts end 

    1 answer 1

    Why do you need to keep an empty basket in the database. It is better to call the Cart.new method and attach User and Items to it and save it with save. In general, the book Agil Web Development (there is a translation in Russian or write me a text) for you, they are considering building a store in detail.

    An example for the controller (you need to implement the correct connections and the current_user method):

    cart1 = Cart.new

    cart1.user_id = current_user.id

    cart1.save

    cart.save

    We need to write a lot for you, I do not know what to write, better go through the book ....

    • Please try to publish detailed answers containing a specific example of the minimum solution, supplementing them with a link to the source. Answers –references (as well as comments) do not add knowledge to the Runet. - Nicolas Chabanovsky