Using Rails 4 and ruby 2.2, I have my User model which has following attributes
- username
- active
Now I need to create a search text field for username, email and drop down for active attributes. I have my
user.rb
def self.usernames(username)
user = all
user = user.where("username LIKE ?", "%#{username}%")
return user
end
def self.emails(email)
user = all
user = user.where("email LIKE ?", "%#{email}%")
return user
end
def self.actives(active)
user = all
user = user.where("active LIKE ?", "%#{active}%")
return user
users_controller.rb
def index
@users = User.all
@users = @users.usernames(params[:username]) if params[:username].present?
@users = @users.emails(params[:email]) if params[:email].present?
@users = @users.actives(params[:active]) if params[:active].present?
end
index.html.erb
h1>Listing Users</h1>
<div id="forms">
<%= form_tag users_path, :method=> "get" do %>
<%= label_tag :username, "Name" %>
<%= text_field_tag :username %>
<%= label_tag :email, "Email" %>
<%= text_field_tag :email%>
<%= label_tag :active, "Active" %>
<%= select_tag :active, options_for_select([['Active', true], ['Inactive', false]]) %>
<%= submit_tag "Search" %>
<%= link_to "Clear Search", request.path, class:"cancel-button" %>
<% end %>
</div>
<div id="users"><%= render "users" %></div>
<%= button_to "Create User", new_user_path, method: :get %>
Now when I am trying to filter by username or email, it is not giving me any result.
Following is the result in console,
Started GET "/users?utf8=%E2%9C%93&username=alok&email=&active=true&commit=Search" for ::1 at 2016-04-18 13:10:09 +0530
Processing by UsersController#index as HTML
Parameters: {"utf8"=>"✓", "username"=>"alok", "email"=>"", "active"=>"true", "commit"=>"Search"}
User Load (1.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? ORDER BY `users`.`id` ASC LIMIT 1 [["id", 11]]
{"utf8"=>"✓", "username"=>"alok", "email"=>"", "active"=>"true", "commit"=>"Search", "controller"=>"users", "action"=>"index"}
User Load (1.0ms) SELECT `users`.* FROM `users` WHERE (username LIKE '%alok%') AND (active LIKE '%true%')
Rendered users/_users.html.erb (7.2ms)
Rendered users/index.html.erb within layouts/application (49.3ms)
Completed 200 OK in 671ms (Views: 550.7ms | ActiveRecord: 49.9ms)
I have referred the following post but getting similar result, no output,Please let me know if I am missing anything,
Multiple search fields in rails
Aucun commentaire:
Enregistrer un commentaire