Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord选择除列之外的其他列_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails ActiveRecord选择除列之外的其他列

Ruby on rails ActiveRecord选择除列之外的其他列,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我可以指定一种方法来选择ActiveRecord中的所有列,除了少数列。例如,对于用户,我不想选择他们的密码哈希或电子邮件。这是可能的还是我必须手动硬编码所有列 谢谢诸如此类的事 exclude_columns = ['password', 'email'] columns = User.attribute_names.delete_if(|x| exclude_columns.include?(x)) User.select(columns) 编辑 我忘了我们可以做阵列1-阵列2 最佳答案

我可以指定一种方法来选择ActiveRecord中的所有列,除了少数列。例如,对于用户,我不想选择他们的密码哈希或电子邮件。这是可能的还是我必须手动硬编码所有列

谢谢诸如此类的事

exclude_columns = ['password', 'email']
columns = User.attribute_names.delete_if(|x| exclude_columns.include?(x))

User.select(columns)
编辑

我忘了我们可以做阵列1-阵列2

最佳答案是:

exclude_columns = ['password', 'email']
columns = User.attribute_names - exclude_columns

User.select(columns)
写一个类似于

def select_without columns
  select(column_names - columns.map(&:to_s))
end

另一个非常有用的方法是在模型中设置一个作用域,以防需要经常避免列

在我的例子中,我将图像保存到blob字段中,因此我希望避免每次以简单的方式加载这些图像:

scope :select_exclude_image, ->  { select( Movie.attribute_names - ['image'] ) }
然后,为了避免选择中的图像,可以执行以下操作:

Movie.select_exclude_image.first


我希望这会有帮助

在某些情况下,特别是当您考虑使用
default\u scope
来排除某些列时,我建议不要使用这种方法,因为在
select
子句之后,with Rails about
count
中断。这可能导致令人惊讶的下游错误


在这种情况下,考虑将记录打破成两个表,一个是必要的数据,另一个是你只需要不时的数据,然后使用关联来访问额外的数据。

只需为希望在默认情况下排除每个查询中的某些列的用户添加一个选项,就可以使用Rails 5功能“忽略列”,顾名思义,该功能将这些列排除在外

代码非常简单:

class User < ApplicationRecord
  self.ignored_columns = %w[password email]
end
class用户

请注意,如果直接访问该属性,
会出现错误,因此,请确保删除列的所有用法
,这样它可能只适用于从不需要使用列的情况。

我会使用
def select_而不使用*列
,这样您就可以使用任意数量的参数。此方法存在问题:
COUNT
在这里不起作用。因此,
Model.select([:a,:b]).count
将抛出一个错误。在这个例子中,
column\u names
是一个类方法。@VitalyDyatlov您可以使用
.size
。我不是SQL专家,但在
select
中放置多个列将导致您看到的错误<代码>计数
是非常低级的SQL。我相信您必须使用“窗口功能”使其在这种情况下工作。类似于
选择*,count(*)over()作为mytable中的总计数。在这种情况下,
size
适合我,但我认为它可能不如
count
length
delete\u准确,如果
应该有花括号。
class User < ApplicationRecord
  self.ignored_columns = %w[password email]
end