Rails has_many with alias name

前端 未结 5 2150
忘掉有多难
忘掉有多难 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: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
    

提交回复
热议问题