mardi 21 février 2017

Ruby on Rails: Keep check boxes selected after search

In my RoR application I have a form whereby users can search for their contacts by first name and select the ones that they want to send an email to. My problem is that after searching for say "Tom", and selecting the checkbox for "Tom", if they then reset the search to display all check boxes "Tom" is no longer selected.

Can someone please tell me how this can be sorted?

The search code is:

<% if @email.current_step == "email_recipients" %>
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search" %>
      </p>
    <% end %>
<% end %>

The check boxes are displayed in a collection through the code:

<%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>

The controller code for the search is:

 def contact_search
    @email = Email.new(session[:email_params])
    @email.current_step == session[:email_step]
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contact_search(params[:search_string])
    if @contacts.empty?
        flash[:notice] = "There are no emails with that subject"
        @contacts = Contact.all
    end
    render :action => "new"
 end

And in the model:

def self.contact_search(search_string)
    self.where("firstname LIKE ?", search_string)
end

I cannot work out how to keep a checkbox selected after a user then searches for something else or resets the search, can someone please shed some light on how this can be achieved?

Aucun commentaire:

Enregistrer un commentaire