Rails has_many with alias name

Ruby on-RailsHas Many

Ruby on-Rails Problem Overview


In my User model I could have:

has_many :tasks

and in my Task model:

belongs_to :user

Then, supposing the foreign key 'user_id' was stored in the tasks table, I could use:

@user.tasks

My question is, how do I declare the has_many relationship such that I can refer to a User's Tasks as:

@user.jobs

... or ...

@user.foobars

Thanks a heap.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Solution 2 - Ruby on-Rails

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks
end

Solution 3 - Ruby on-Rails

If you use has_many through, and want to alias:

has_many :alias_name, through: :model_name, source: :initial_name

(thanks for the correction Sami Birnbaum)

Solution 4 - Ruby on-Rails

To complete @SamSaffron's answer :

You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :

class BlogPost
  has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post  
end

and you need to make sure you have the belongs_to attribute on the child model:

class BlogPostImage
  belongs_to :blog_post
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoctororangeView Question on Stackoverflow
Solution 1 - Ruby on-RailsSam SaffronView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPwnrarView Answer on Stackoverflow
Solution 3 - Ruby on-RailsA. AskarovView Answer on Stackoverflow
Solution 4 - Ruby on-RailsGhisView Answer on Stackoverflow