如何启用ActiveRecord以支持CJK查询?

时间:2015-06-22 00:56:35

标签: ruby-on-rails activerecord

rails console之后,我可以执行以下查询:

 1.9.3-p551 :001 > ActivityObject.where(:title => "kiketurpis integer aliquet")

我在数据库中得到了一个独特的答案。但如果我进入:

1.9.3-p551 :002 >   ActivityObject.where(:title => '第一个纵纹')

(在双引号中有一个中文字符串。)我得到了表activity_objects中的所有记录,这意味着我不能在谓词where中使用中文字符串。

另外,我可以使用psql下的中文字符串直接查询此记录:

vish_development=# select * from activity_objects where title = '第一个纵纹';

所以我的问题是,我应该怎样做才能在ActiveRecord CJK string中启用where或者像这样?

1 个答案:

答案 0 :(得分:1)

Frederick Cheung在maillist Ruby on Rails: Talk回答我之后,我终于找到了答案。

现在它运作正常!

因为ruby 1.9不使用utf-8作为默认编码:

 1.9.3-p551 :001 > __ENCODING__.name
 => "US-ASCII" 

对于UTF-8,我使用了以下命令:

 bash-3.2$ export LANG=en_US.UTF-8
 bash-3.2$ rails c
 Loading development environment (Rails 3.2.22)
  1.9.3-p551 :001 > __ENCODING__.name
  => "UTF-8" 

之后,当我运行上一个查询时,我得到了正确的记录:

1.9.3-p551 :002 > ActivityObject.where(:title => '第一个纵纹')

 ActivityObject Load (29.5ms)  SELECT "activity_objects".* FROM "activity_objects" WHERE "activity_objects"."title" = '第一个纵纹'
=> [#<ActivityObject id: 648, created_at: "2015-06-21 14:41:19", updated_at: "2015-06-21 14:41:19", object_type: "Excursion", like_count: 0, title: "第一个纵纹", description: "整的行不?", follower_count: 1, visit_count: 5, language: "independent", age_min: 0, age_max: 0, notified_after_draft: false, comment_count: 0, popularity: 0, download_count: 0, qscore: 500000, reviewers_qscore: nil, users_qscore: nil, ranking: 0, title_length: 1, desc_length: 1, tags_length: 1, scope: 0, avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil, avatar_updated_at: nil, teachers_qscore: nil>]