Where + block - 不工作
Where + block - not working
用户有多个帐号,帐号有一个角色。我需要检查至少有一个帐户具有条件设置为 true 的角色:
@current_user.accounts.where { |x| x.role.some_condition? }.exists?
但是ArgumentError: wrong number of arguments (0 for 1)
连这个都不行
@current_user.accounts.where { |x| true } # the same error
@current_user.accounts.where(true) # ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR: argument of AND must be type boolean, not type integer
试试这个,使用 Enumerable#any?
:
@current_user.accounts.any? { |x| x.role.some_condition? }
您可以使用 any?
来执行此操作,因为所选答案指出了这一点。但这将加载您的所有帐户,然后然后过滤它们。
如果条件是在角色 table 中设置的标志,则以下是您想要的。
@current_user.
accounts.
joins(:role).
where(roles: {some_column_in_roles_table: true}).
group("accounts.id").
exists?
用户有多个帐号,帐号有一个角色。我需要检查至少有一个帐户具有条件设置为 true 的角色:
@current_user.accounts.where { |x| x.role.some_condition? }.exists?
但是ArgumentError: wrong number of arguments (0 for 1)
连这个都不行
@current_user.accounts.where { |x| true } # the same error
@current_user.accounts.where(true) # ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR: argument of AND must be type boolean, not type integer
试试这个,使用 Enumerable#any?
:
@current_user.accounts.any? { |x| x.role.some_condition? }
您可以使用 any?
来执行此操作,因为所选答案指出了这一点。但这将加载您的所有帐户,然后然后过滤它们。
如果条件是在角色 table 中设置的标志,则以下是您想要的。
@current_user.
accounts.
joins(:role).
where(roles: {some_column_in_roles_table: true}).
group("accounts.id").
exists?