# Has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/has-and-belongs-to-many/174739>\
**Category:** IT\
**Created:** [September 1, 2009, 2:41pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many/174739 "2009-09-01T14:41:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Salvatore](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ea666f/32.png) [@Salvatore](https://www.ruby-forum.com/u/Salvatore)\
**Post date:** [September 1, 2009, 2:41pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many/174739/1 "2009-09-01T14:41:22Z")

</div>

Ciao ragazzi, ho un problema che non riesco a risolvere, spero che  
qualcuno possa illuminarmi, allora:

ho le seguenti tabelle:

```
create_table :carts do |t|
  t.belongs_to :user
  t.boolean :escapee, :default => 0
  t.timestamp :escapee_at
  t.timestamps
end

create_table "products" do |t|
  t.column " id", :integer
  t.column "name", :string
end

create_table "carts_products", :id => false, :force => true do |t|
  t.column "cart_id", :integer
  t.column "product_id", :integer
  t.column "quantity", :integer
end

```

e il seguente modello

class Cart \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :products

```
def self.update_carts(session_cart)
    cart = self.find(:first, :order => "created_at DESC", :limit =>

```

1, :conditions =\> “escapee=0”)  
product\_ids = []  
session\_cart.each do |id, item|  
product\_ids \<\< [id]  
end  
cart.update\_attributes(:product\_ids =\> product\_ids)  
end  
end

Dal controller:  
…  
if logged\_in?  
current\_user.carts.update\_carts session[:cart]  
end  
…

Volevo sapere come poter incrementare il campo quantità qualora il  
record esista. Spero di essere stato chiaro nel farvi capire cosa  
cerco.

Un grazie in anticipo a tutti quelli che risponderanno.

Ciao ciao,

Salvatore

---

<div class="post-metadata">

**Author:** ![Salvatore](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ea666f/32.png) [@Salvatore](https://www.ruby-forum.com/u/Salvatore)\
**Post date:** [September 1, 2009, 2:56pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many/174739/2 "2009-09-01T14:56:00Z")

</div>

2009/8/1 Salvatore [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> end
> 
> create\_table “carts\_products”, :id =\> false, :force =\> true do |t|  
> t.column “cart\_id”, :integer  
> t.column “product\_id”, :integer  
> t.column “quantity”, :integer  
> end

ciao,  
quando la tabella associativa contiene altri campi oltre ai due id,  
per quel che so non si usa has\_and\_belongs\_to\_many ma has\_many  
through,  
così:

class Cart \< ActiveRecord::Base  
has\_many :carts\_products  
has\_many :products, :through =\> :carts\_products  
end

class Products \< ActiveRecord::Base  
has\_many :carts\_products  
has\_many :carts, :through =\> :carts\_products  
end

class CartsProduct \< ActiveRecord::Base # nota: plurale/singolare  
belongs\_to :cart  
belongs\_to :product  
end

poi potrai usare @cart.products e @product.carts, ma anche  
@cart.carts\_products.first().quantity.

per quello che vuoi fare, credo ti basti aggiungere pochi metody alle  
classi, o forse ancora meglio all’associazione, modificando l’esempio  
riportato in

> **[ActiveRecord::Associations::ClassMethods](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)**
>
> Active Record Associations Associations are a set of macro-like class methods for tying objects together through foreign keys.

class Account \< ActiveRecord::Base  
has\_many :people do  
def find\_or\_create\_by\_name(name)  
first\_name, last\_name = name.split(" ", 2)  
find\_or\_create\_by\_first\_name\_and\_last\_name(first\_name,  
last\_name)  
end  
end  
end

person = Account.find(:first).people.find\_or\_create\_by\_name(“David  
Heinemeier H.”)  
person.first\_name # =\> “David”  
person.last\_name # =\> “Heinemeier H.”

pietro
