生成ActiveRecord包含来自string的哈希

问题描述 投票:0回答:1

我有这样的架构:

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}}

我希望我很清楚......

ruby-on-rails ruby activerecord
1个回答
0
投票

我会考虑在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} 

免责声明:我独立使用过这些东西,但从未尝试过。因此,如果它无法工作,请告诉我,我可以尝试适当地更新我的答案。

© www.soinside.com 2019 - 2024. All rights reserved.