如何使用某些ID过滤掉表中的某些对象? (Rails 4,Postgresql)

时间:2016-05-09 09:35:46

标签: ruby-on-rails postgresql

在我提出问题之前,我会提供一些背景信息。

我有3个相互影响的模型。

Scoreboard has many Teams. Team belongs to Scoreboard.

以下使用through表。

Scoreboard many-to-many with User.(let's call this Scoreboard.followers)

Team many-to-many with User.(Let's call this Team.members)

我有一个Team_Members控制器,使用以下方法:

Team_member#new方法:

def new 
        @selected = true
        @scoreboard = Scoreboard.find(params[:scoreboard_id])
        @team = Team.find(params[:team_id])
        @team_members = @team.members
        @followers = @scoreboard.followers.search(params[:search]).paginate(page: params[:page], per_page: 50)
end

我尝试做的是在new.html.erb视图中显示所有Scoreboard followers。我可以搜索它们并将成员添加到与Team相关联的Scoreboard.

这里是 new.html.erb 视图:

<%= form_tag(new_scoreboard_team_team_member_path, :method => "get", id: "member-search-form", autocomplete: "off") do %>
<div class="row new-member-field">
    <div class="col-xs-12 col-sm-6">
        <%= text_field_tag :search, params[:search], placeholder: "Filter Members by Name", class:"form-control" %>
    </div>
</div>
<% end %>

<% if @followers.any? %>  

        <% @followers.each do |follower| %>
            <div class="row member-follower-div" id="follower_<%=follower.id%>">
                <div class="col-xs-10 col-sm-5 member-prof-link">
                    <%= link_to follower.name, user_path(follower.id) %>
                </div>
                <div class="col-xs-2 col-sm-1 member-add">
                    <%= link_to (add_scoreboard_team_team_member_path(@scoreboard,@team, follower)), method: :post, remote: true, :data => {:disable_with => ".."} do %>
                        <i class="fa fa-plus-square fa-lg" aria-hidden="true"></i>
                    <% end %>
                </div>
            </div>
        <% end %> 

        <div class="row">
            <div class="col-xs-12 col-sm-6 new-member-pages">
                <%= will_paginate @followers %>
            </div>
        </div>

<% end %>

现在好的问题。问题出现在控制器方法中。 @ team.members和@ scoreboard.followers都是来自Users表的源对象。 如何从@ team.members中存在的@ scoreboard.followers中过滤掉用户对象?我不想在我的视图中显示@followers属于@ team.members系列。 此外,作为奖励,我想按字母顺序按用户名命名粉丝。

我尝试了.where("users.id NOT IN (?)", @team_members.pluck(:id)),但如果@team_members集合为空,则页面上不会显示任何结果。

1 个答案:

答案 0 :(得分:0)

我这样解决了:

def new 
        @selected = true
        @scoreboard = Scoreboard.find(params[:scoreboard_id])
        @team = Team.find(params[:team_id])
        @team_members = @team.members
        if (@team_members.any?)
           @wonderful_humans = @scoreboard.favourited_by.where("users.id NOT IN (?)", @team_members.pluck(:id)).search(params[:search]).sort_by{ |a| a.name.downcase }
        else
           @wonderful_humans = @scoreboard.favourited_by.search(params[:search]).sort_by{ |a| a.name.downcase }
        end
        @followers = @wonderful_humans.paginate(page: params[:page], per_page: 50)
    end