我有这样的架构:
user
has_many post_values
belongs_to author
has_many addresses
class User < ActiveRecord::Base
has_many :post_values
end
class PostValue < ActiveRecord::Base
belongs_to :user
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :post_values
has_many :addresses
end
class Address < ActiveRecord::Base
belongs_to :author
end
这个模式只是一个例子,并不反映真实案例。
现在我有一个这样的字符串:post_values_author_addresses
。
在Rails库中存在一个库或一个gem或一个方法,给定该字符串返回我的关联哈希:{post_values: {author: :addresses}}
?
我知道Ransack做了类似于其范围的事情......
我需要这样的方法:
User.get_associations(:post_values_author_addresses) => {post_values: {author: :addresses}}
我希望我很清楚......
我会考虑在PostValue
类中添加'has_one_through ...'关联。
has_many :addresses, :through => :author
与Addresses
相反
has_many :PostValues, :through => :author
您可能需要使用inverse_of选项将事物联系在一起,但如果您的命名是常规的,那么您可能会没事。
本页描述了它的用法:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
然后,您可以使用PostValue.reflect_on_all_associations
查找与您的字符串匹配的关联。我没有尝试使用:through
协会,但很有可能你会在name属性中找到你需要的东西。就像是:
PostValue.reflect_on_all_associations.select {|a| a.name == my_string}
免责声明:我独立使用过这些东西,但从未尝试过。因此,如果它无法工作,请告诉我,我可以尝试适当地更新我的答案。