首页 > 解决方案 > 仅显示用户(订阅 = 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?)

标签: ruby-on-rails

解决方案


我认为你的错误在这里:

Software.includes(:users).where(user: {subscribed: true})

includes应该反映关联,在这种情况下是单数user。这就是导致您看到的错误的原因。

此外,这是一个常见的陷阱,但where子句中的关联需要使用表名。

尝试这个:

Software.includes(:user).where(users: { subscribed: true })

这假设您将使用user其他地方的信息,即在您的视图中。如果您不需要访问记录,而只是检查user查询,您可以切换includesjoins以提高查询效率:

Software.joins(:user).where(users: { subscribed: true })

这是一个单独的主题,但这里有一个很好的阅读


推荐阅读