Rails has_many with alias name

前端 未结 5 2123
忘掉有多难
忘掉有多难 2020-12-12 09:36

In my User model I could have:

has_many :tasks

and in my Task model:

belongs_to :user

Then, supposing the

相关标签:
5条回答
  • 2020-12-12 10:11

    If you use has_many through, and want to alias:

    has_many :alias_name, through: model_name, source: initial_name
    
    0 讨论(0)
  • 2020-12-12 10:13

    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
    
    0 讨论(0)
  • 2020-12-12 10:17

    Give this a shot:

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

    Note, that :as is used for polymorphic associations.

    0 讨论(0)
  • 2020-12-12 10:18

    You could do this two different ways. One is by using "as"

    has_many :tasks, :as => :jobs
    

    or

    def jobs
         self.tasks
    end
    

    Obviously the first one would be the best way to handle it.

    0 讨论(0)
  • 2020-12-12 10:30

    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
    
    0 讨论(0)
提交回复
热议问题