# Initialization of inverted models

**URL:** <https://www.ruby-forum.com/t/initialization-of-inverted-models/131300>\
**Category:** Rails\
**Created:** [March 7, 2008, 8:24pm UTC](https://www.ruby-forum.com/t/initialization-of-inverted-models/131300 "2008-03-07T20:24:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![byrnejb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/d2c977/32.png) [@byrnejb](https://www.ruby-forum.com/u/byrnejb)\
**Post date:** [March 7, 2008, 8:24pm UTC](https://www.ruby-forum.com/t/initialization-of-inverted-models/131300/1 "2008-03-07T20:24:24Z")

</div>

Given the following situation:

client belongs\_to entity

entity has\_one client  
entity has\_one vendor  
entity has\_many contacts  
entity has\_many sites  
etc.

Creating a new client should test if an entity with the existing name is  
already on file and return it if so, else the process should create a  
new entity with identically named attributes in entity passed the  
initial values from client.  
I think that this sort of complexity belongs in the client model but I  
am open to arguments as to where else it might go.

Is there a recommended Rails approach that deals with this situation?  
Should I do all this creating and initializing in a before\_create  
specified method?

---

<div class="post-metadata">

**Author:** ![byrnejb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/d2c977/32.png) [@byrnejb](https://www.ruby-forum.com/u/byrnejb)\
**Post date:** [March 8, 2008, 1:59am UTC](https://www.ruby-forum.com/t/initialization-of-inverted-models/131300/2 "2008-03-08T01:59:21Z")

</div>

James B. wrote:

> Given the following situation:
> 
> client belongs\_to entity
> 
> entity has\_one client  
> entity has\_one vendor  
> entity has\_many contacts  
> entity has\_many sites  
> etc.

class SomeController \< ApplicationController  
def find\_or\_create\_client  
# Don’t use find :first as it will throw  
found = Entity.find(:all, :conditions =\> [‘matching\_field = ?’,  
params[:entity][:matching\_field]])  
if found.blank?  
# Please refer to rails casts on how to do creates through  
associations  
# I think it’s complex forms part 1, 2, and 3  
@client = Entity.create(params[:entity]).client  
else  
@client = found.first.entity.client  
end  
end  
end

hth

ilan
