Ruby-on-rails 带有别名的 Rails has_many

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1163032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:31:00  来源:igfitidea点击:

Rails has_many with alias name

ruby-on-railshas-many

提问by doctororange

In my User model I could have:

在我的 User 模型中,我可以:

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_id”存储在任务表中,我可以使用:

@user.tasks


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

我的问题是,如何声明 has_many 关系,以便我可以将用户的任务称为:

@user.jobs

... or ...

... 或者 ...

@user.foobars

Thanks a heap.

谢谢一堆。

回答by Sam Saffron

Give this a shot:

试一试:

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

Note, that :asis used for polymorphic associations.

请注意,这:as用于多态关联

回答by Pwnrar

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

alias_attribute如果您仍然希望能够将它们称为任务,您也可以使用:

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

  has_many :tasks
end

回答by Ghis

To complete @SamSaffron's answer :

要完成@SamSaffron 的回答:

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

您可以class_nameforeign_key或一起使用inverse_of。我个人更喜欢更抽象的声明,但这真的只是一个品味问题:

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

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

并且您需要确保belongs_to在子模型上具有该属性:

class BlogPostImage
  belongs_to :blog_post
end

回答by Brent Kirby

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.

显然,第一个将是处理它的最佳方法。