Cristhian Boujon
Cristhian Boujon

Reputation: 4190

Ruby on Rails - column name is the same that relationship name

I'm working with a legacy database and I cannot change it.

user
---------
user_id | name | plan
1         'bob'   20

plan is a foreign key to plan table. So in RoR, if I write User.find(1).plan I get 20 but I want to get the plan object

class User < ActiveRecord::Base
    belongs_to :plan, :foreign_key => :plan # this causes conflict because the names should not be equal

Can I change the name of accessor column in Rail?

Upvotes: 2

Views: 568

Answers (1)

beck03076
beck03076

Reputation: 3308

Try this,

:class_name is what you are looking for.

class Plan < ActiveRecord::Base
  has_many :users, :foreign_key => 'user_id'
end

class User < ActiveRecord::Base
  belongs_to :alpha, :class_name => 'Plan', :foreign_key => 'plan'
end

Upvotes: 2

Related Questions