# Problema fixtures

**URL:** <https://www.ruby-forum.com/t/problema-fixtures/127213>\
**Category:** IT\
**Created:** [January 26, 2008, 10:46am UTC](https://www.ruby-forum.com/t/problema-fixtures/127213 "2008-01-26T10:46:33Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![cpecchia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/77aa72/32.png) [@cpecchia](https://www.ruby-forum.com/u/cpecchia)\
**Post date:** [January 26, 2008, 10:46am UTC](https://www.ruby-forum.com/t/problema-fixtures/127213/1 "2008-01-26T10:46:33Z")

</div>

Salve ragazzi,  
ho riscontrato la seguente stranezza con le fixtures.

Ho due modelli:

class Entity \< ActiveRecord::Base  
has\_many :users  
belongs\_to :owner, :class\_name =\> ‘User’

```
validates_presence_of :owner

```

end

class User \< ActiveRecord::Base  
has\_many :entities # entities created by the user (he is its owner)  
belongs\_to :entity # entity (one) the user belongs to  
end

Giocando in console tutto va a meraviglia, setto l’owner, la  
validazine lavora…tutto ok.

Avendo questa fixture:

– entities.yml

prima\_entity:  
name: Una entità a caso  
description: nulla da dire  
url: [http://www.example.org](http://www.example.org)  
owner: carlo

il problema nasce con la riga “owner”, il DB non vuol saperne, la  
mappa nella colonna “owner” (che ovviamene non esiste nel DB, è  
presente solo user\_id).  
Ho provato anche con:  
user: carlo  
ma niente…

Any tips?

---

<div class="post-metadata">

**Author:** ![cpecchia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/77aa72/32.png) [@cpecchia](https://www.ruby-forum.com/u/cpecchia)\
**Post date:** [January 26, 2008, 12:15pm UTC](https://www.ruby-forum.com/t/problema-fixtures/127213/2 "2008-01-26T12:15:56Z")

</div>

Ciao Carlo,  
Questa è una relazione ‘molti a molti’, dovresti gestirla con  
has\_and\_belongs\_to\_many:

[http://wiki.rubyonrails.org/rails/pages/has\_and\_belongs\_to\_many](http://wiki.rubyonrails.org/rails/pages/has_and_belongs_to_many)

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

class Entity \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :owners, :class\_name =\> ‘User’  
end

class User \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :entities  
end

Inoltre dovresti creare una join table chiamata esattamente  
‘entities\_users’.

C’è un altro modo per gestire le relazioni habtm, fortemente  
raccomandata nel caso in cui tu voglia aggiungere attributi alla join  
table, che così diventa un model object a tutti gli effetti.

class Ownership \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :entity  
end

class Entity \< ActiveRecord::Base  
has\_many :ownerships  
has\_many :owners, :through =\> :ownerships, :source =\> :user  
end

class User \< ActiveRecord::Base  
has\_many :ownerships  
has\_many :entities, :through =\> :ownerships  
end

Luca.

---

<div class="post-metadata">

**Author:** ![cpecchia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/77aa72/32.png) [@cpecchia](https://www.ruby-forum.com/u/cpecchia)\
**Post date:** [January 26, 2008, 12:40pm UTC](https://www.ruby-forum.com/t/problema-fixtures/127213/3 "2008-01-26T12:40:48Z")

</div>

Un attimo un attimo… mi sono spiegato male.  
Rettifico:

- un utente può creare molte entità, ogni entità ha un unico  
creatore (chiamato owner)
- un utente può essere associato ad una sola entità (non  
necessariamente creata da lui…)

Per questo pensavo al modello proposto… Quello che mi lascia  
perplesso è il malfunzionamento delle fixtures…

2008/1/26, Luca G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

---

<div class="post-metadata">

**Author:** ![cpecchia](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/77aa72/32.png) [@cpecchia](https://www.ruby-forum.com/u/cpecchia)\
**Post date:** [January 26, 2008, 1:34pm UTC](https://www.ruby-forum.com/t/problema-fixtures/127213/4 "2008-01-26T13:34:55Z")

</div>

Ho risolto il “problema” (che comunque avevo mal posto… sorry).

Ogni entità è creata da un utente, il quale è l’ “owner” per tale  
entità.Inoltre un utente può, facoltativamente, essere associato ad una  
particolare entità (non necessariamente creata da lui stesso).

Quanto appena detto nel codice diventa:

## db/migrate/002\_create\_entity

class CreateEntities \< ActiveRecord::Migration  
def self.up  
create\_table :entities do |t|  
t.column :name, :string  
t.column :owner\_id, :integer  
t.timestamps  
end  
add\_column :users, :entity\_id, :integer  
end

def self.down  
remove\_column :users, :entity\_id  
drop\_table :entities  
end  
end

## app/models/user.rb

class User \< ActiveRecord::Base  
has\_many :entities # entities created by the user (that’s its owner)  
belongs\_to :entity # entity the user belongs to  
end

## app/models/entity.rb

class Entity \< ActiveRecord::Base  
has\_many :users  
belongs\_to :owner, :class\_name =\> ‘User’, :foreign\_key =\> ‘owner\_id’

validates\_presence\_of :owner  
end

## db/fixtures/entities.yml

pippo:  
name: Pippo  
owner: carlo

## db/fixtures/users.yml

carlo:  
username: carlo  
entity: pippo

Adesso il seguente test non mi dà alcun problema:

## test/unit/entity\_test.rb

require File.dirname( **FILE** ) + ‘/…/test\_helper’

class EntityTest \< ActiveSupport::TestCase  
def setup  
@e = entities(:pippo)  
end

def test\_valid\_owner  
@e.owner = nil  
assert !@e.valid?  
end  
end

In realtà “era ovvio” (a posteriori…), tutto sta nel definire la  
corretta FK nella tabella entities ed associarla opportunamente nel  
modello:

# db/migrate/002\_create\_entity

t.column :owner\_id, :integer

# app/models/entity.rb

belongs\_to :owner, :class\_name =\> ‘User’, :foreign\_key =\> ‘owner\_id’  
validates\_presence\_of :owner

In questo modo possiamo avere più “ruoli” per l’associazion  
utente-entità (es: creatore, manuntentore, ecc.)
