我有一个has_many
关联,并且我希望只提取具有特定值ID的关联记录,并且仅当一个条件为true时。
例如:
class Account
has_many :issues
has_many :nodes, through: :issues
end
class Issue
belongs_to :account
has_many :nodes, dependent: :destroy, # where node.account_id == [1,2,3,5] if self.account.trial_account
end
class Node
belongs_to :account
belongs_to :issue
end
因此,基本上,如果帐户是试用帐户,那么issue.nodes
将只返回4条记录。
我会在Issue上使用不同的方法:
class Issue
...
def effective_nodes # or visible_nodes or so
if account.trial_account?
nodes
else
nodes.limit(4) # or your static nodes
end
end
您可以为关联定义提供某种lambda。类似这样的东西:
has_many :nodes, -> (issue) do
where(account_id: [1,2,3,5]) if issue.account.trial_account
end
我不确定我是否正确理解了这个问题,但从代码库中我看到该节点属于帐户AND问题。
使用我的示例中的这个代码块,将返回属于请求问题的节点AND属于id为1,2,3或5的帐户。
如果你需要获得任何只属于id为1,2,3或5的帐户的节点,我认为更好的方法是坚持@stwienert解决方案,定义一个返回正确节点的方法。