Rails 4 has_many through:过滤来自两个关联模型的记录

时间:2016-09-28 15:53:10

标签: ruby-on-rails-4 activerecord has-many-through model-associations

模型关联

class User < ActiveRecord::Base
  has_many :boards
  has_many :cards, through: :boards
end

class Board < ActiveRecord::Base
  belongs_to :user
  has_many :cards
end

class Card < ActiveRecord::Base
 belongs_to :board
end

检索记录

卡片和纸板模型有一个名为“关闭”的属性。 当我检索属于current_user的所有卡时,我想过滤出'closed'等于true的板卡和卡片。

即。
如果board.closed == true,则该板及其所有相关卡被过滤掉 如果card.closed == true,则此个人卡被过滤掉


这不起作用,但显示了我想要做的事情:

current_user.cards.where(card.closed == false, card.board.closed == false)

2 个答案:

答案 0 :(得分:1)

Card
  .joins(:board)
  .where(
    cards:  { closed: false },
    boards: { user_id: current_user.id, closed: false }
  )

或者,如果你坚持从current_user开始:

current_user
  .cards
  .joins(:board)
  .where(cards: { closed: false }, boards: { closed: false })

答案 1 :(得分:0)

我能够用以下方法过滤出已关闭的牌和属于封闭牌的牌:

current_user.cards.to_a.delete_if { |card| card.board.closed == true || card.closed == true }
相关问题