Filter users by using checkboxes for profile data in Rails
I was looking over this previous 开发者_如何学编程post on using checkboxes to filter results in Rails but got kinda lost. I'm new to programming but want to filter Users on my index page depending on what profile data is checked in a sidebar. Ideally, the index page would start out with all Users, then filter down depending on the checkboxes. Here's relevant info from my User and Profile models, User controller, and the index.html.erb file:
User model:
class User < ActiveRecord::Base
attr_accessor :password, :email
validates :email, :uniqueness => true,
:length => { :within => 5..50 },
:format => { :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i }
validates :password, :confirmation => true,
:length => { :within => 4..20 },
:presence => true,
:if => :password_required?
has_one :profile, :dependent => :destroy
Profile model:
class Profile < ActiveRecord::Base
attr_accessible :field_1, :field_2, :field_3, :field_4...
belongs_to :user
User controller:
def index
@user = User.all
end
Index.html.erb:
<% form_for 'user' do |f| %>
<table id="Criteria">
<tr>
<td class="main head">Fields</td>
<td></td>
</tr>
<tr>
<td class="head">Field_1:</td>
<td></td>
</tr>
<tr>
<td class="normal"><%= current_user.profile.field_1 %></td>
<td><% check_box_tag :field_1 %></td>
</tr>
If anyone can help explain it I'd appreciate it very much! (And if more info is needed let me know.)
I guess, you should take a look at Meta Search gem. I used it to solve similar problem here http://omaris.kg/categories/2-zhenskaya-obuv
UPD
I have Item
model where i defined scopes which filter items according to user request. Below is the scope which filter by brands:
scope :by_brands, lambda {|brands|
brands = brands.delete_if {|i| i == "" } if brands.present?
return if brands.blank?
composed = self.scoped
composed = composed.where("brand_id IN (?)", brands)
composed
}
Then i created class method searchy(search)
(didn't find any better name XD) where i call every scope one after another like self.by_brands(search[:brands]).by_price_range(search[:from], search[:to])...
search
parameter is going to be params[:searchy]
Then i used like Item.searchy(params[:search])
in my controller. params[:searchy]
are got from form_for
block in the view.
That's it, i guess )
P.S.: For the first time i wanted to use MetaSearch gem to use its heplers in my form. But i did without it and build my own
精彩评论