# How do you clean up this cryptic code?

**URL:** <https://www.ruby-forum.com/t/how-do-you-clean-up-this-cryptic-code/55583>\
**Category:** Rails\
**Created:** [March 22, 2006, 8:17am UTC](https://www.ruby-forum.com/t/how-do-you-clean-up-this-cryptic-code/55583 "2006-03-22T08:17:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![calyth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/b4bc9f/32.png) [@calyth](https://www.ruby-forum.com/u/calyth)\
**Post date:** [March 22, 2006, 8:17am UTC](https://www.ruby-forum.com/t/how-do-you-clean-up-this-cryptic-code/55583/1 "2006-03-22T08:17:31Z")

</div>

So, I’m coding my school project in Rails.  
There are two models, User and Restaurants.  
I noticed that in Restaurants, when you use the belongs\_to method, you  
could specify the condition of the associated table. There are a few  
types of users, in the user\_type column of the users table - owners is  
type 1, users are type 2.  
So in my haste to hand in enough code, in the Restaurant model, I wrote:  
belongs\_to :owner, :class\_name =\> “User”, :foreign\_key =\> “owner\_id”,  
:conditions =\> “user\_type =1”  
That worked fine. But my teammates may do something with this code.  
So what I tried to do was to add a hash into the User model:  
TYPE = { “user”=\>2,“owner”=\>1 }.freeze  
But when I modified the belong\_to line to  
belongs\_to :owner, :class\_name =\> “User”, :foreign\_key =\> “owner\_id”,  
:conditions =\> [“user\_type = :owner”,User::TYPE]  
WebBRICK says NoMethodError exception has been raised with:  
private method `gsub’ called for [“user\_type = :owner”, {“user”=\>2,  
“admin”=\>0, “owner”=\>1}]:Array  
If I use [“user\_type = ?”,User::TYPE[‘owner’]] instead, the same  
exception gets raised.  
So how exactly should I clean up this cryptic code?

---

<div class="post-metadata">

**Author:** ![calyth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/b4bc9f/32.png) [@calyth](https://www.ruby-forum.com/u/calyth)\
**Post date:** [March 22, 2006, 12:33pm UTC](https://www.ruby-forum.com/t/how-do-you-clean-up-this-cryptic-code/55583/2 "2006-03-22T12:33:45Z")

</div>

Benton L. wrote:

> So, I’m coding my school project in Rails.  
> There are two models, User and Restaurants.  
> I noticed that in Restaurants, when you use the belongs\_to method, you  
> could specify the condition of the associated table. There are a few  
> types of users, in the user\_type column of the users table - owners is  
> type 1, users are type 2.

You should try Single Table Inheritance thing:

class User \< ActiveRecord::Base  
end

class Owner \< User  
end

class Restaurant \< ActiveRecord::Base  
belongs\_to :owner  
end

Don’t forget to add varchar “type” column to your “users” table.

Find more info on STI here:  
[http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance](http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance)
