简体   繁体   English

Rails JSON过滤器关联结果

[英]Rails JSON filter association results

Users (with name) can have cards (with name) through collections (with number): 用户(具有名称)可以通过集合(具有编号)获得卡片(具有名称):

class User < ActiveRecord::Base
    has_many :collections
    has_many :cards, through: :collections
end
class Card < ActiveRecord::Base
    has_many :collections
    has_many :users, through: :collections
end
class Collection < ActiveRecord::Base
    belongs_to :user
    belongs_to :card
end

My cards API includes all cards and collections information: 我的卡片API包含所有卡片和收藏信息:

class CardsController < ApplicationController
    def index
        @cards = Card.all
        render json: @cards, :include => :collections
    end
end

I would like to remove collections not owned by user queryparam. 我想删除不属于用户queryparam的集合。 I tried: 我试过了:

@cards = @cards.includes(:collections).where(collections: { user_id: [nil, params[:user]] }) if params[:user].present?

It correctly outputs cards that the user owns and cards that nobody owns, but it filters out cards that are only owned by other users. 它可以正确输出用户拥有的卡和没人拥有的卡,但是可以过滤出仅由其他用户拥有的卡。 I would like to have these too (all cards, including collections information only for the current user). 我也想拥有这些卡(所有卡,包括仅适用于当前用户的收藏信息)。

Try this in your CardsController : 在您的CardsController尝试CardsController

@cards = Card.includes(:collections).filtered_cards(current_user.id).sort_by { |t| t.created_at }.reverse!

then in your Card model create a scope that filters out the user's cards, and the collections are not owned by anyone: 然后在您的Card模型中创建一个范围,该范围将用户的卡片过滤掉,并且集合不归任何人所有:

scope :filtered_cards, -> (user_id) {
  select { |card| card.collections.each { |col| col.user_id == user_id }.length > 0 || card.user_id == nil }
}

or 要么

scope :filtered_cards, -> (user_id) {
  select { |card| card.collections.map(&:user_id).include?(user_id) || card.user_id = nil }
}

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM