在联合表中搜索

时间:2013-09-30 15:18:42

标签: ruby-on-rails-3 search has-and-belongs-to-many

我需要一些帮助才能在我的视图中添加搜索字段。

我有一张家庭餐桌,每个家庭都有0-n册。我想进行搜索,只显示特定书籍的家庭。

现在我正在使用ransack进行其他一些简单的搜索:

的Controler:

class FamiliesController < ApplicationController
  def index
    @search = Family.search(params[:q])
    @families = @search.result    

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @families }
    end
  end

模型:

class Family < ActiveRecord::Base
  has_many :names
  has_and_belongs_to_many :books, :join_table => "books_families"
  has_and_belongs_to_many :races, :join_table => "families_races"

  attr_accessible :descr, :nome, :book_ids, :race_ids

  validates :nome, uniqueness: true, presence: true
end

查看:

<fieldset>
  <legend>Filter for families</legend>
  <%= search_form_for @search do |f| %>
    <div class="field">
    <%= f.label :nome, "Name: " %><br />
    <%= f.text_field :nome_cont, :class => "search-field"%>
    </div>
  <div class="actions">
    <%= f.submit "Search" %>
  </div>
  <% end %>
</fieldset>

<table>
  <tr>
    <th><%= sort_link(@search, :nome, "Name") %></th>
    <th>Books</th>
    <th>Descr</th>
  </tr>
(...)
    <td>
      <ol type="disc">
        <% family.books.each do |book| %>
          <li> <%= book.nome %> </li>
        <% end %>
      </ol>
    </td>
(...)

我该怎么办?

2 个答案:

答案 0 :(得分:0)

我不熟悉ransack,但您的查询应该可以通过SQL实现。我不知道你的所有表/字段名称,但是这样的东西应该有效。

@families = Family.where("families.id IN(SELECT books_families.family_id FROM 
                          books_families WHERE books_families.book_id IN( 
                          SELECT books.id FROM books WHERE books.title LIKE(?)))",
                          "%" + params[:q] + "%")

答案 1 :(得分:0)

终于得到了解决方案。它简单的2行:

  <div class="field">
    <%= f.label :books_id_eq, "Livro:" %><br />
    <%= f.collection_select :books_id_eq, Book.order(:nome), :id, :nome, :include_blank => "Todos" %> 
  </div>