I am running Rails 4, using the rails-jquery-autocomplete gem - I have everything hooked up so it works fine to autocomplete models where there is a :name column.
What I'm struggling with is how to autocomplete a name where it is an instance method. I have a model that looks like this:
class Roster < ActiveRecord::Base
belongs_to :practice
belongs_to :role
belongs_to :compensation_type
def name
self.practice.name + ' - ' + self.role.role_type.name + ' (' + self.role.name + ') - ' + self.compensation_type.name
end
end
This should make it fairly easy to see what I'm trying to do - autocomplete on the name method.
The method itself works:
2.2.2 :002 > roster1.name
Practice Load (0.2ms) SELECT "practices".* FROM "practices" WHERE "practices"."id" = ? LIMIT 1 [["id", 1]]
Role Load (0.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = ? LIMIT 1 [["id", 1]]
RoleType Load (0.2ms) SELECT "role_types".* FROM "role_types" WHERE "role_types"."id" = ? LIMIT 1 [["id", 1]]
CompensationType Load (0.3ms) SELECT "compensation_types".* FROM "compensation_types" WHERE "compensation_types"."id" = ? LIMIT 1 [["id", 1]]
=> "Test Practice - Role Name Test (Role Type Test) - Test Comp Type"
So the problem seems to be the autocomplete. The form loads, and I can see in the console that the following error is thrown:
Started GET "/bookings/autocomplete_roster_name?term=Te" for ::1 at 2015-08-22 09:18:32 +0100
Processing by BookingsController#autocomplete_roster_name as JSON
Parameters: {"term"=>"Te"}
Roster Load (0.9ms) SELECT rosters.id, rosters.name FROM "rosters" WHERE (LOWER(rosters.name) LIKE 'ar%') ORDER BY LOWER(rosters.name) ASC LIMIT 10
SQLite3::SQLException: no such column: rosters.name: SELECT rosters.id, rosters.name FROM "rosters" WHERE (LOWER(rosters.name) LIKE 'Te%') ORDER BY LOWER(rosters.name) ASC LIMIT 10
Completed 500 Internal Server Error in 6ms (ActiveRecord: 1.4ms)
The first obvious thing is that the SQL is totally different - it isn't trying to pull together the three pieces of info and combine them, it's just looking for a :name column.
Is there a way to make this work with a custom instance method instead of an actual column? Can I make my instance method behave like a column?
For completeness, my controller for the form:
autocomplete :roster, :name
and on my form I have:
<%= f.input :roster, as: :autocomplete, url: autocomplete_roster_name_bookings_path, id_element: '#booking_roster_id', input_html: { class: 'form-control' } %>
Any help greatly appreciated!