使用跨模型范围在索引页面上过滤表单

时间:2011-09-19 03:17:18

标签: ruby-on-rails filter scope

我想使用在不刷新页面的情况下使用复选框过滤的表单来过滤索引页面。它是Users索引,但我根据Profile数据进行过滤。我是编程的初学者,并设法将我想要做的一些事情拼凑在一起,但需要帮助将它们连接起来。 (供参考,有关我使用this article的范围的指导,以及我使用this article的表单/ ajax / jQuery。)

User.rb:

class User < ActiveRecord::Base
  has_one :profile, :dependent => :destroy
  scope :profiles, lambda {
    joins(:profiles).group("users.id") & Profile.id
  }
end

Profile.rb:

class Profile < ActiveRecord::Base
  belongs_to :user
  class << self
    def search(q)
      [:high_school, :higher_ed, :current_city, :job_title, :hometown, :subject].inject(scoped) do |combined_scope, attr|
        combined_scope.where("profiles.#{attr} LIKE ?", "%#{q}%")
      end
    end
  end
end

UsersController:

class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def update
    @user = current_user
    @user.update_attributes(params[:user])
  end

  def search
    if params[:profiles].blank?
      raise "You must provide search criteria."
    end
    params[:profiles] = "%#{params[:profiles]}%"
    conditions    = " Description LIKE :term"

    @users = User.all(
        :conditions => [conditions, params],
        :offset     => params[:offset],
        :limit      => params[:limit]
    )

    respond_with @users
  end
end

ProfilesController:

class ProfilesController < ApplicationController
  before_filter :authenticate, :only => [:edit, :update]

  def index
    @profile = current_user.profile
  end

  def update
    @profile = user.profile
    if @profile.update_attributes(params[:profile])
      redirect_to profile_path, :notice => 'Updated user information successfully.'
    else
      render :action => 'edit'
    end
  end
end

routes.rb中:

resources :users do
    get "search/:term/:offset/:limit.:format", :action => "search", :constraints => { :offset => /\d+/, :limit => /\d+/ }
end

来自index.html.erb的示例:

<%= form_tag users_path, :id => 'users_index', :method => :get, :remote => true  do %>
<table>
  <tr>
    <td class="normal"><%= current_user.profile.high_school %></td>
    <td><%= check_box_tag 'high_school', :class => 'submittable' %></td>
  </tr>
</table>
<% end %>

我的用户在index.html.erb上呈现的位置:

<div class="searchresults">
  <div id="wall">
    <% @users.each do |user| %>
    <% end %>
  </div>
</div>

index.js.erb的:

$("#wall").html("<%= escape_javascript(render(@users)) %>");

有人可以帮我弄清楚我做错了吗?

1 个答案:

答案 0 :(得分:0)

  1. form_for @user来电更新。你应该这样做:

    = form_tag“/ users / search”,:method =&gt; :获得

  2. ???我想我们需要查看您的javascript代码。

  3. 总体而言,我强烈建议您将代码放在一边并按照ryan bate's screencast for advanced search form进行,现在要解决/改进很多事情。