我有以下内容:
Account --> Options
Account --> Profiles --> Options
以下是模型
# models/account.rb
class Account < ActiveRecord::Base
has_many :accounts_has_options
has_many :options, :through => :accounts_has_options
has_many :accounts_has_profiles
has_many :profiles, :through => :accounts_has_profiles
end
# models/profile.rb
class Profile < ActiveRecord::Base
has_many :profiles_has_options
has_many :options, :through => :profiles_has_options
has_many :accounts_has_options
has_many :accounts, :through => :account_has_options
end
# models/option.rb
class Option < ActiveRecord::Base
has_many :accounts_has_options
has_many :accounts, :through => :accounts_has_options
has_many :profiles_has_options
has_many :profiles, :through => :profiles_has_options
end
我希望所有与帐户关联的选项以及通过配置文件关联的所有选项,可能都在虚拟属性中。
我在这个问题中找到了一个例子: How do you concatenate two active record results to return a new result that can further be filtered? 但是他们只有两个模型,在我的例子中,我们在故事中有一个连接表。
任何想法,如何编写这样的虚拟属性?
答案 0 :(得分:0)
如何将这样的方法添加到您的帐户模型
def all_options
profile_option_ids = []
self.profiles.map{|p| profile_option_ids = profile_option_ids + p.options.pluck("options.id")}
Option.where("id IN (?) or id IN (?)", self.options, profile_option_ids)
end
所以你只需要打电话
account.all_options