1

我需要一些帮助才能在我的视图上放置一个搜索字段。

我有一张家庭表,每个家庭都有 0-n 本书。我想搜索仅显示特定书籍的家庭。

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

控制器:

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

我应该怎么办?

4

2 回答 2

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>
于 2014-01-22T12:09:56.180 回答
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] + "%")
于 2013-10-03T00:32:40.510 回答