【发布时间】:2017-10-27 09:44:20
【问题描述】:
我正在尝试取消多个模型的范围,如下所示 具有acts_as_paranoid的用户模型
class User
acts_as_paranoid
has_one :category
has_one :brand
has_one :item
INDEXED_FIELDS = {
only: [:name],
include: {
category: { only: [:name] },
item: { only:[:name] },
brand: { only: [:name]},
}
}
def custom_json
Category.unscoped do
Item.unscoped do
Brand.unscoped do
self.as_json(INDEXED_FIELDS)
end
end
end
end
end
用户模型有以下关联,也有acts_as_paranoid
Sample Category model, Brand 和 Item model 有相同的代码
class Category
acts_as_paranoid
belongs_to :user
end
我可以用“N”个模型动态地做到这一点吗,比如遍历数组,如下所示
def custom_json
[Category, Item, Brand].each do
# do unscoping
end
end
联想看起来像
【问题讨论】:
-
你想通过取消范围来做什么??
-
@NarasimhaReddy 我想从多个模型中排除默认范围条件
-
没关系。但是一次取消多个模型的范围是什么情况。我们可以边做边做吗?
-
请提供
Category、Item、Brand模型文件。所以我们可以看到它们之间的关系 -
当我们调用
self.as_json(INDEXED_FIELDS)时,它会查询关联来构建json,我想要unscope关联并构建json。
标签: ruby-on-rails ruby activerecord acts-as-paranoid