Ransack Ruby 在 Rails 结果不会呈现

Ransack Ruby On Rails Result Wont Render

我一直在尝试将 Ransack 搜索 gem 实施到我目前正在从事的项目中。我很确定我已经正确设置了它。我希望能够搜索配置文件并将我的代码放在配置文件控制器中,如下所示:

def index
 @q = Profile.search(params[:q])
 @profile = @q.result(distinct: true)
 @profiles = Profile.all
end

配置文件 index.html.erb 文件如下所示:

<%= search_form_for @q do |f| %>
 <div class="field">
 <%= f.label :first_name_cont, "Name Contains" %>
 <%= f.search_field :first_name_cont %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>

它至少看起来是在尝试正确搜索数据库,但不会在屏幕上呈现任何结果。这可能是我没有看到的显而易见的事情。非常感谢任何帮助。

是您尝试访问@profile 时遇到的问题,还是只是知道如何显示结果?如果是后者,现在它们存储在@profile 中,因此您需要遍历它们并从每个配置文件实例中选择要显示的内容。

从我使用这个 gem 开始,它似乎默认为给定 class 的索引页面(所以在您的情况下,是个人资料索引页面)。所以你可以:

  1. 只需将结果列在您在上面共享的搜索表单下方即可。
  2. 将搜索栏移至主页控制器之类的位置,这样当进行搜索时,它将转到个人资料索引页面并仅显示结果。

在您的控制器中尝试这样的设置并查看:

 #profile controller
  def index
    @search = Profile.search(params[:q])
    @profiles = @search.result(distinct: true)
  end

  #profile index
  <%= search_form_for @search do |f| %>
    <%= f.label :first_name_cont, "name in profile" %><br>
    <%= f.submit "Search", class:"btn btn-info btn-block" %>
  <% end %>

  <% @profiles.each do |profile| %>
    <%= profile.name %>
  <% end %>