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.)