Ruby on rails 标识与SQL查询没有付款关联的资源

Ruby on rails 标识与SQL查询没有付款关联的资源,ruby-on-rails,join,activerecord,Ruby On Rails,Join,Activerecord,我有一个索引页,我想在其中显示功能板和标准板。特色板有一次付款,标准板没有 class Payment < ApplicationRecord belongs_to :board end class Board < ApplicationRecord has_one :payment end 现在,我想通过以下操作获取标准列表: Board.where(category: category, confirmed: true) 但这同时返回了功能板和标准板 Board.j

我有一个索引页,我想在其中显示功能板和标准板。特色板有一次付款,标准板没有

class Payment < ApplicationRecord
  belongs_to :board
end

class Board < ApplicationRecord
  has_one :payment
end
现在,我想通过以下操作获取标准列表:

Board.where(category: category, confirmed: true)
但这同时返回了功能板和标准板

Board.joins(:payment).where(category: category, confirmed: true)

我正在寻找一种方法来获取标准列表(没有付款的董事会),但我就是不知道如何做到这一点。

在董事会模型中创建一个新列

class AddPaymentToBoards < ActiveRecord::Migration
  def change
    add_column :boards, :payment, :boolean, default: false
  end
end
Board.rb

def payment_made
  self.update_attribute(:payment, true)
end 
如果你张贴代码,你使用创建一个付款,我可以帮助你更多,但它应该是微不足道的

然后您可以创建一个作用域

scope :payment_made, -> { where payment: true }
然后,您将能够使用
Board.payment\u made
返回payment布尔属性为true的板

Board
  .joins("LEFT JOIN payments ON boards.id = payments.board_id")
  .where(payments: {id: nil})

我强烈建议你。它还解释了您的使用案例:您首先离开加入支付的董事会,然后过滤掉所有有支付的董事会。

更具组合性的处理方式是:

Board.references(:payment).where.not(payment: { id: nil })
我们鼓励您充分利用示波器。例如:

class Board
  scope :with_payments, -> { includes(:payment) }
  scope :featured, -> { with_payments.where.not(payment: { id: nil }) }
end

Board.featured # => SELECT * FROM boards JOIN payments ON payments.board_id = board.id AND payments.id IS NOT NULL;

请参阅下面编辑的答案,我发现明确请求我的帮助,然后忽略我的答案是相当不礼貌的…@TheCha͢mp您的答案引导我走上了正确的方向应该是
加入(“在董事会上加入左加入付款。id=付款。董事会id”)