强烈推荐一个高级查询插件Searchgasm

让你复杂的查询代码变得更加优雅:

下面是一个查询用户(User)的例子:
关系:UserGroup => User => Order (=> = has_many)
可查询条件:first_name(包含),total(Order中,大于),name(开始于)

Controller的代码
# app/controllers/users_controller.rb
class UsersController < ApplicationController
    def index
        @search = User.new_search(params[:search])
        @users, @users_count = @search.all, @search.count
    end
end

View的代码
# app/views/users/index.html.erb
<% if @users_count > 0 %>
    <%= @users_count %> users found

    <table border="1" cellpadding="5">
        <tr>
            <th><%= order_by_link :id %></th>
            <th><%= order_by_link :user_group => :name %></th>
            <th><%= order_by_link :first_name %></th>
            <th><%= order_by_link :last_name %></th>
            <th><%= order_by_link [:email, :first_name] %></th>
        </tr>
        <% @users.each do |user| %>
            <tr>
                <td><%= user.id %></td>
                <td><%= user.user_group ? user.user_group.name : "-" %></td>
                <td><%= user.first_name %></td>
                <td><%= user.last_name %></td>
                <td><%= user.email %></td>
            </tr>
        <% end %>
    </table>

    <br />
    <br />

    Per page: <%= per_page_select %>

    <% if @search.page_count > 1 %>
        <br />Page: <%= page_select %>
    <% end %>
<% else %>
    No users were returned
<% end %>

# app/views/users/index.html.erb
<% form_for @search do |f| %>
    <fieldset>
        <legend>Search Users</legend>

        <% f.fields_for @search.conditions do |users| %>
            First name keywords:<br />
            <%= users.text_field :first_name_keywords %><br />
            <br />

            <% users.fields_for users.object.orders do |orders| %>
                Has orders with a total greater than:<br />
                $<%= orders.text_field :total_gt %><br />
                <br />
            <% end %>

            <% users.fields_for users.object.user_group do |user_group| %>
                Belongs to user group with name that starts with:<br />
                <%= user_group.text_field :name_starts_with %><br />
                <br />
            <% end %>
        <% end %>
    </fieldset>
    <%= f.submit "Search" %>
<% end %>


看见没,controller里面的代码相当简洁,在view里面定义查询条件时,还可以使用后缀:
_keywords表示contains(顺便说一下_keywords是contains的扩展,一个真正的关键字搜索。它过滤一些无意义的词语,如“and”,“the”等。),
_gt表示大于,
_starts_with表示以某某开头。。。。
太方便了,还自带翻页,可选AJAX。。。。。
大家自己看吧
DEMO: http://searchgasm_example.binarylogic.com/rails_ajax/users
更多介绍: Tutorial: Pagination, ordering, and searching with Searchgasm
插件下载: http://github.com/binarylogic/searchgasm/tree/master

你可能感兴趣的:(html,Ajax,F#,Ruby,Rails)