How do you clean up this cryptic code?


#1

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?


#2

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