Rails—通过关联作为字符串从has_many =>获取名称

时间:2022-09-23 08:00:22

I have three models

我有三个模型

class Mar < ActiveRecord::Base
  belongs_to :baz
  belongs_to :koo
end

class Baz < ActiveRecord::Base
  has_many :other_mars, :class_name => "Mar", :foreign_key => :b
end

class Koo < ActiveRecord::Base
  has_many :mars
  has_many :bazs, :through => :mars, :source => :baz
end

and from the model Baz I would like to get the has_many name as a string. In this example it is "other_mars"

我想从Baz模型中获得has_many名称作为字符串。在这个例子中是"other_mars"

The solution would have to work for any similar has_many relationship with a class_name passed to it.

该解决方案必须适用于与传递给它的class_name的任何类似的has_many关系。

I am using Rails 3.2 and ruby 1.9

我正在使用Rails 3.2和ruby 1.9

2 个解决方案

#1


1  

If I understand your requirement correctly, the following code helps

如果我正确地理解了您的需求,下面的代码将会有所帮助

result = Baz.reflect_on_all_associations.collect do |association|
  association.name.to_s if association.options[:class_name].present?
end.compact

In your case the above code results ['other_mars']. i.e it returns all the associations declared with the :class_name key.

在您的示例中,上面的代码将产生['other_mars']。我。它返回用:class_name键声明的所有关联。

#2


1  

I would like to get the has_many name as a string. In this example it is "other_mars"

我希望将has_many名称作为字符串。在这个例子中是"other_mars"

If what you are looking for is the related association for a model, in your case Baz open up your rails console in the project directory and type:

如果您正在寻找的是一个模型的相关关联,在您的案例中,Baz在项目目录中打开您的rails控制台并输入:

Baz.reflect_on_all_associations(:has_many)

This will return an ActiveRecord object with the a list of the associations under the attribute @name.

这将返回一个ActiveRecord对象,其中包含属性@name下的关联列表。

So the name of the association to a string can be obtained by typing

因此,可以通过输入来获得与字符串的关联的名称

Baz.reflect_on_all_associations(:has_many).name.to_s

#1


1  

If I understand your requirement correctly, the following code helps

如果我正确地理解了您的需求,下面的代码将会有所帮助

result = Baz.reflect_on_all_associations.collect do |association|
  association.name.to_s if association.options[:class_name].present?
end.compact

In your case the above code results ['other_mars']. i.e it returns all the associations declared with the :class_name key.

在您的示例中,上面的代码将产生['other_mars']。我。它返回用:class_name键声明的所有关联。

#2


1  

I would like to get the has_many name as a string. In this example it is "other_mars"

我希望将has_many名称作为字符串。在这个例子中是"other_mars"

If what you are looking for is the related association for a model, in your case Baz open up your rails console in the project directory and type:

如果您正在寻找的是一个模型的相关关联,在您的案例中,Baz在项目目录中打开您的rails控制台并输入:

Baz.reflect_on_all_associations(:has_many)

This will return an ActiveRecord object with the a list of the associations under the attribute @name.

这将返回一个ActiveRecord对象,其中包含属性@name下的关联列表。

So the name of the association to a string can be obtained by typing

因此,可以通过输入来获得与字符串的关联的名称

Baz.reflect_on_all_associations(:has_many).name.to_s