rails仅在嵌套资源存在时进行查询



我有一个rails应用程序。我只想在配置文件存在的情况下显示用户(用户只有一个配置文件)。据我所知,由于我在index.html.erb中有一组,我不能简单地使用<%如果user.profile%>,所以我想在控制器中过滤它。

我应该如何更改查询以仅从数据库中获取具有配置文件的用户?

通常,检查嵌套资源是否存在的最佳方法是什么?在带有查询的控制器中执行,还是仅在视图中执行?

用户/控制器.rb

def index
    @q_users = User.ransack(params[:q])
    @users = @q_users.result(distinct: true).includes(:profile).paginate(page: params[:page], per_page: 12)
end

index.html.erb

<div class="user-profile-index" style="padding-right:20px;padding-left:20px;">
  <% @users.each_slice(3) do |users_for_row| %>
    <div class="row">
      <%= render :partial => "user", :collection => users_for_row, as: :user %>
    </div>
  <% end %>
</div>

_user.html.erb

<div class="col-md-4">
  <%= link_to user do %>
    <div class="panel panel-info">
      <div class="panel-heading">
      </div>
      <div class="panel-body">
        <% if user.profile %>
        <% if user.profile.avatar %>
          <%= image_tag user.profile.avatar.url(:base_thumb), class: "avatar" %>
        <% end %>
        <h4><%= user.profile.first_name %> <%= user.profile.last_name %></h4>
        <h5><%= user.profile.company %></h5>
        <% end %>
        <h5><%= user.email %></h5>
      </div>
    </div>
  <% end %>
</div>

user.rb

has_one :profile, dependent: :destroy

profile.rb

belongs_to :user

includes(:profile)替换为:

joins(:profile).preload(:profile)

joins将为您提供INNER JOIN,它将只选择具有配置文件的用户。preload将预加载在joins中找到的配置文件(以避免N+1问题)。您还可以将此联接移动到用户模型中的一个单独范围中,例如with_profile

最新更新