ruby-on-rails - 仅显示用户(订阅 = true)的软件
问题描述
我有一个 Ruby on rails 应用程序,用户可以在其中添加一个或多个软件。然后这些用户可以订阅(付费模式)。
我希望能够仅显示所有付费用户软件。
我尝试了几件事,但仍然找不到解决方案。
例如:
Software.includes(:users).where(user: {subscribed: true})
编辑:
型号用户:
class User < ActiveRecord::Base
has_many :softwares
end
模型软件:
class Software < ActiveRecord::Base
belongs_to :user
end
连接表
class CreateJoinTableUsersSoftwares < ActiveRecord::Migration[5.2]
def change
create_join_table :users, :softwares do |t|
t.index [:user_id, :software_id]
t.index [:software_id, :user_id]
end
end
end
错误:
Software.includes(:users).where(user: {subscribed: true})
ActiveRecord::ConfigurationError (Can't join 'Software' to association named 'users'; perhaps you misspelled it?)
解决方案
我认为你的错误在这里:
Software.includes(:users).where(user: {subscribed: true})
includes
应该反映关联,在这种情况下是单数user
。这就是导致您看到的错误的原因。
此外,这是一个常见的陷阱,但where
子句中的关联需要使用表名。
尝试这个:
Software.includes(:user).where(users: { subscribed: true })
这假设您将使用user
其他地方的信息,即在您的视图中。如果您不需要访问记录,而只是检查user
查询,您可以切换includes
到joins
以提高查询效率:
Software.joins(:user).where(users: { subscribed: true })
这是一个单独的主题,但这里有一个很好的阅读。
推荐阅读
- javascript - 在 PHP 中增加会话变量的问题。它只增加一次
- azure-ad-b2c - Azure AD B2C - 具有 HRD、域提示和 MFA 的自定义策略
- javascript - 无需重新加载页面即可进行幻灯片放映
- powershell - 输出文件时使用 Powershell 环境变量作为字符串
- laravel - Eloquent:转换一个 sql 请求
- modelica - 在 Dymola 中使用和不使用内联集成有什么区别?
- javascript - React Router 在 else 中加载任何一个组件
- python - 根据其他列值创建一个新列 - 条件前向填充?
- mongodb - MongoDB 按 id 对文档进行分组并从文档中合并匹配的数组元素
- c# - 如何从 HoloLens 2 上的 Edge 接收自定义协议深层链接到 Unity 2019 UWP 应用程序?