2013-09-30 38 views
1

我需要一些幫助將搜索字段放在我的視圖上。在聯合表中搜索

我買了一張家庭桌子,每個家庭都有0-n本書。我想搜索只顯示特定書籍的家庭。

現在我使用洗劫其他一些簡單的搜索:

的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> 
(...) 

我應該怎麼做?

+0

因此,您希望用戶搜索一本書,並且您的代碼返回與該書關聯的所有家庭,對嗎? – Arvoreniad

+0

是的,那我需要 – Techmago

+0

我的答案是否解決您的問題? – Arvoreniad

回答

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> 
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] + "%") 
+0

直到現在我還沒有測試過它。不,沒有工作: >> @search !! # 我只注意到我不知道如何在sql – Techmago

+0

中執行相同的查詢我檢查了我的代碼,看起來有幾個語法錯誤。我糾正了他們。這個SQL假設你有一個名爲'families'和'id'列的表。一個名爲'books'的表,至少有一個'id'和'title'列,還有一個表,它將兩個名爲'books_families'的表與一個'book_id'列和一個'family_id'列鏈接起來。如果這些字段/表在您的結尾有不同的名稱,您可以在查詢中自行更改它們,也可以將它們發佈到此處,我可以幫助您。 – Arvoreniad

+0

@Techmago答覆已更新 – Arvoreniad