Rails 4 using Carmen gem cannot convert country name in query

394 Views Asked by At

i am using the carmen gem to store the country as their country code like for United states it is US . but when i retrieve the country in the view i retrieve it as their full name

i have a model user and account

class User < ActiveRecord::Base
      has_one :account
    end

 class Account < ActiveRecord::Base
      belongs_to :User
    end 

and

 @users = User.includes(:admin, :account).
       where.not(admin: { role: 'SUPER' }).where("names like ? OR accounts.country like ?" , "%#{ search }%", "%#{ search }%")

<% @users.each do |user| %>
  <%= user.names %>
  <%= Carmen::Country.coded(user.account.country).name %>
<% end %>

i have a user query which i have used in the view to find user names with their country but in the search like if i write US it gives me all the names of with country United states but i dont want to search the name with their country code , i want to write the whole country name

i know the issue is in the search query. the country code is stored in the database, so it is searching by the code , but i cant find out how to use carmen country code to their name conversion in the search query Please help , thankx in advance

1

There are 1 best solutions below

1
On

You can get Carmen Country object using fuzzy matching (actually use Regular Expression) by passing extra option fuzzy: true that is default false to Carmen::Country.named() method.

country = Carmen::Country.named('bang')

return nil but

  country = Carmen::Country.named('bang', fuzzy: true) 

return <#Carmen::Country name="Bangladesh">. Now you can get country 2 alpha code using country.alpha_2_code that return "BD" similarly alpha 3 code using country.alpha_3_code that you can use to you query.

N.B: Since here use fuzzy it will not give always right answer( I think most of the case :)) unless search key is close to actual word.

If I search Carmen::Country.named('ban', fuzzy: true) it return <#Carmen::Country name="Albania"> though I was expecting <#Carmen::Country name="Bangladesh">.

You can find about fuzzy in lib/carmen/querying.rb( my carmen version is 1.0.2). I think it may help someone.

Edited Though it's not best answer, you can save actual name to another column named like country_name which value will be set using after_save rails call back. Be careful about calling any active record update method with in callback that call callback method may cause infinite loop. You can use update_column that does not call callback.