andy
andy

Reputation: 2399

Belongs_to different field name

I've inherited quite a weird table layout:

callbacks
id, note, user

admin
id, name, password

In callbacks, the user is set to the name of the admin rather than the actual ID. Now I need to be able to call callbacks.user and have rails lookup the admin with that name and then bind it to that record.

I have a model for admin that is called users

How would I go about that?

Upvotes: 0

Views: 1542

Answers (1)

tihom
tihom

Reputation: 8003

You can override the default methods.

def user
  User.find_by_name(user_name)
end

def user=(obj)
  self.user_name = obj.name
end

def user_name
  self[:user]
end

def user_name=(name)
  self[:user] = name
end

Other option , to make it work with belongs_to, there is primary_key option but need to have a different name than the attribute user

 # Callback.rb
 belongs_to :user_model , :class => "User", :foreign_key => :user, :primary_key => :name

 # User.rb
 has_one :callback , :foreign_key => :user, :primary_key => :name

Upvotes: 2

Related Questions