Jump to content

The ultimate community for Ruby on Rails developers.


Photo

manipulating with values during search - remove diacritic


  • Please log in to reply
4 replies to this topic

#1 swigrid

swigrid

    Passenger

  • Members
  • 8 posts

Posted 25 November 2013 - 06:08 PM

hi guys,

 

i would need to remove diacritic during search. I'm tried something like this

scope :no_diacritic, lambda { name = I18n.transliterate(name) }

thanks



#2 Ohm

Ohm

    Guard

  • Members
  • 180 posts
  • LocationCopenhagen

Posted 25 November 2013 - 06:58 PM

This scope doesn't make any sense. You are trying to set the variable name (I can only imagine it is part of the model in use) dynamically when calling the scope. The will not work.

 

Your solution could lie here: http://stackoverflow...b=votes#tab-top with the unaccent method from PostgreSQL.


Blog: http://ohm.sh | Twitter: madsohm


#3 swigrid

swigrid

    Passenger

  • Members
  • 8 posts

Posted 25 November 2013 - 07:10 PM

hi Ohm,

 

thanks for quick reply. I know that didn't make any sense, but couldnt it express different way. I come across the solution you proposed but that means I would have to go for PostgreSQL database solution right?

 

isn't there anything where I could manipulate result of search somehow?



#4 Ohm

Ohm

    Guard

  • Members
  • 180 posts
  • LocationCopenhagen

Posted 25 November 2013 - 07:19 PM   Best Answer

Depends on what you want to do. You could do the comparison in Ruby, e.g. having an array of names

["René", "Miguel", "Çeyrek"]

and then mapping I18n.transliterate over it

["René", "Miguel", "Çeyrek"].map {|name| I18n.transliterate(name) }

---

 

You could also set up an search column in your database, stripping the accents from the data. This could be done in a migration like so

class AddSearchColumn < ActiveRecord::Migration
  def self.up
    add_column :people, :search_name, :string
    
    People.find_each do |person|
      person.save(validate: false)
    end
  end

  def self.down
    remove_column :people, :search_name
  end
end

having added a before save to the model

class Person < ActiveRecord::Base
  ...
  before_save :update_search_name
  ...

  private
    def update_search_name
      self.search_name = I18n.transliterate(name)
    end
end

Blog: http://ohm.sh | Twitter: madsohm


#5 swigrid

swigrid

    Passenger

  • Members
  • 8 posts

Posted 25 November 2013 - 07:31 PM

thanks again, let me play with it but looks like i will end up with shadow column of the field where diacritic needs to be removed






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users