【问题标题】:Rails 4 has_many through: filtering records from both associated modelsRails 4 has_many through:过滤来自两个关联模型的记录
【发布时间】:2023-04-03 02:15:01
【问题描述】:

模型协会

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

检索记录

Card 和 Board 模型有一个称为“关闭”的属性。 在检索属于 current_user 的所有卡片时,我想过滤掉“关闭”等于 true 的板和卡片。


如果 board.close == true,则过滤掉该板及其所有关联卡片
如果 card.close == true,则过滤掉这张卡片


这不起作用,但显示了我正在尝试做的事情:

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

【问题讨论】:

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


    【解决方案1】:

    我能够过滤掉封闭的卡片和属于封闭板的卡片:

    current_user.cards.to_a.delete_if { |card| card.board.closed == true || card.closed == true }
    

    【讨论】:

    • 这很糟糕,因为它是 Ruby 处理的,并且可能会杀死你所有的内存。查看我对 ActiveRecord 查询的回答
    【解决方案2】:
    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 })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多