Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias for relationship

I have this:

  class User < ActiveRecord::Base
    has_many :jobs

How can I rename ":jobs" to something else without renaming the source class? I just want to be to refer to them as:

  class User < ActiveRecord::Base
    has_many :obligations

and that's it. I've tried:

has_many :obligations, source: :user

but it didn't work.


2 Answers

You are doing wrong. Instead of adding source add class like this

class User < ActiveRecord::Base
  has_many :obligations,   class_name: 'Job'
end

I hope this will solve your problem.

like image 130
sohail khalil Avatar answered Jan 26 '26 07:01

sohail khalil


If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name.

you have to use :class_name option

class User < ActiveRecord::Base
  has_many :obligations, class_name: 'Job'
end
like image 22
Deepak Mahakale Avatar answered Jan 26 '26 08:01

Deepak Mahakale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!