mardi 21 février 2017

Ruby on Rails: Why isn't my search working?

In my RoR application I am allowing users to select contacts that they want to send an email to. The users select these contacts via checkboxes on the form. I am trying to add in search functionality so that a user can search by first name and only check boxes with contacts that match that search appear.

To do this I am trying to use this code on the view:

<div class="form-group">
    <label>From Email Address</label></br>
    <% @useraccounts.each do |useraccount| %>
        <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
        <%= f.label :account_id, useraccount.account.email, :value => "true"  %><br>
    <% end %>
</div>
<div class="form-group">
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search", :name => nil %>
      </p>
    <% end %>
    <label>Contacts</label></br>
    <%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>
</div>

Where the @contacts instance variable holds the contacts returned from the search in the controller.

When a user clicks the search button, the below controller action should be invoked.

def contact_search
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contacts_search(params[:search_string])
    if @contacts.empty?
        flash.now[:alert] = "There are no contacts with that name."
        @contacts = Contact.all
    end
    render :action => "new"
end

This controller action uses the contact_search method, which is in the Contact.rb model:

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

I also have the contact_search in the routes:

post 'emails/contact_search', :to => 'emails#contact_search'
get 'emails/contact_search', :to => 'emails#contact_search'

But for some reason, when a user clicks search they get a NoMethodError in Emails#create undefined method 'each' for nil:NilClass on the form. The error is as pictured.

enter image description here

I cannot work out why this isn't working, can someone please help?

Aucun commentaire:

Enregistrer un commentaire