[英]rails get a list of records by checking if association is approved
I've got a organization model and an organization_profile model. 我有一个组织模型和一个organization_profile模型。 The organization_profile model has an approved column.
Organization_profile模型具有一个批准的列。 I would like to be able to find all approved users by calling something like: Organization.approved.
我希望能够通过调用以下内容来找到所有批准的用户:Organization.approved。 I found that the best way to handle this is probably through scope.
我发现处理此问题的最佳方法可能是通过作用域。 However I can't seem to get it to work.
但是我似乎无法使其正常工作。 This is what i am trying
这就是我正在尝试的
scope :approved, -> {joins(:organization_profile).where('organization_profile.approved = ?', true) }
But then Organization.approved gives me all kinds of errors: 但是然后Organization.approved给了我各种各样的错误:
Organization Load (8.0ms) SELECT "organizations".* FROM "organizations" INNER JOIN "organization_profiles" ON "organization_profiles"."user_id" = "organizations"."id" WHERE (organization_profile.approved = 't')
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "organization_profile"
LINE 1: ...profiles"."user_id" = "organizations"."id" WHERE (organizati...
^
: SELECT "organizations".* FROM "organizations" INNER JOIN "organization_profiles" ON "organization_profiles"."user_id" = "organizations"."id" WHERE (organization_profile.approved = 't')
Can anyone tell me the correct code? 谁能告诉我正确的密码?
Your query is using organization_profile
(singular) but your table name is organization_profiles
(plural). 您的查询使用的是
organization_profile
(单数),但是表名是organization_profiles
(复数)。
A slightly better way to do this (which also avoids using strings), is to turn the where clause into an Arel predicate (might not be the right word): 一种更好的方法(也避免使用字符串)是将where子句转换为Arel谓词(可能不是正确的词):
scope :approved, -> { joins(:organization_profile).where(OrganizationProfile.arel_table['approved'].eq(true)) }
条件是SQL代码,该代码应正确反映始终为复数形式的表名:
where('organization_profiles.approved = ?', true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.