So I have two resources: group
and user
. When I'm on a group
's show.html.erb page, I want to be able to click a link that creates a popup with a search form to search through all users. I've gotten to the point where I click the 'add user' link and a popup comes up with a search form. The search form functions, the only issue is that I am directed to the users
index page for the results whereas I want the results to appear in this popup.
My thought would be to move what I have in user's index.html.erb into the popup and then have the search form function via ajax. I'm not quite sure how to implement this however especially given that I want to run a search for the user
resource via the group
controller/view.
Group's show.html.erb
<div id="add_user"><%= link_to '(Add User)', '#' %></div>
<div class="popup" id="user_search_form">
<%= form_tag users_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Find User", :name => nil, class: "btn btn-primary" %>
<% end %>
<div id="close_window"><%= link_to 'Cancel', '#' %></div>
</div>
Group's Controller
def show
@group = Group.find(params[:id])
end
User's Controller
def index
@users = User.search(params[:search]).paginate(page: params[:page])
end
User's index.html.erb
<u1 class="users">
<div class="container-fluid">
<%= render @users %>
</div>
</u1>
Thanks in advance. Any help would be much appreciated!
Add the javascript code to handle the searching. This code simply calls the users#index
action via ajax.
/views/groups/show.html.erb
add the new lines.
<div id="add_user"><%= link_to '(Add User)', '#' %></div>
<div class="popup" id="user_search_form">
<%= form_tag users_path, :method => 'get', :id => 'user-search' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Find User", :name => nil, class: "btn btn-primary" %>
<% end %>
<div id="users-result"></div>
<div id="close_window"><%= link_to 'Cancel', '#' %></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('form#user-search').on('submit',function(event){
event.preventDefault();
var url = $(this).attr('action');
var type = $(this).attr('method');
var data = { search : $(this).find(#'search').val() };
$.ajax({
url: url,
type: type,
data: data,
success: function (data) {
$('#users-result').html(data);
}
});
});
});
</script>