如何在rails中使用hstore模块

首先解释一下什么是 hstore

hstorepostgresql 自带的一个模块,可以在字段内用 key/value 格式存储文档数据。

rails4 开始已经在自带的PostgreSQLAdapter中加入了hstore的支持。使用方式如下。

class CreateProfiles < ActiveRecord::Migration
  #启用hstore模块

  enable_extension 'hstore' unless extension_enabled?('hstore')
  def change
    create_table :profiles do |t|
      t.hstore 'settings'
      t.timestamps
    end
    #可以给hstore字段加索引,, 类型有 gin 和 gist

    add_index :profiles, :settings, using: :gin
  end
end

关于 gingist 索引格式的选择, 请看官方文档。

In choosing which index type to use, GiST or GIN, consider these performance differences:

GIN index lookups are about three times faster than GiST

GIN indexes take about three times longer to build than GiST

GIN indexes are moderately slower to update than GiST indexes, but about 10 times slower if fast-update support was disabled (see Section 54.3.1 for details)

GIN indexes are two-to-three times larger than GiST indexes

As a rule of thumb, GIN indexes are best for static data because lookups are faster. For dynamic data, GiST indexes are faster to update. Specifically, GiST indexes are very good for dynamic data and fast if the number of unique words (lexemes) is under 100,000, while GIN indexes will handle 100,000+ lexemes better but are slower to update.

Note that GIN index build time can often be improved by increasing maintenance_work_mem, while GiST index build time is not sensitive to that parameter.

GINGiST 索引快三倍,但也多花了三倍时间。

postgresql 的其他模块用法可以在官方文档找到

其中注意,保存完 hstore 字段后的数据, 如果要修改时, 需要执行字段名_will_change! 这个方法

## you need to call _will_change! if you are editing the store in place

profile.settings["color"] = "green"
profile.settings_will_change!
profile.save!

如何在HABTM中添加唯一认证

先创建has_many_and_belongs_to_many表结构

create_join_table :products, :categories do |t|
  t.index :product_id
  t.index :category_id
end

在model中添加下列代码

class Product < ActiveRecord::Base
  has_and_belongs_to_many, -> { uniq}
end

如何在slim中添加空格

在slim中如果想在两端代码中间添加一个空格,可以通过下面的方式

= link_to "btn1", "#", :class => "btn"
'
= link_to "btn2", "#", :class => "btn"

加一个'

但代码好丑~

重新开始写blog

准备开始新的blog日志, 记录最近的学习情况。

近期一直在搞手游,学习了OC, C++,lua, 再次确定对C++的无爱,再次确认了写的越多,出bug的几率越多。

近期主力工作语言: lua
学习语言: elixir

elixir 是运行在erlang vm上的, 结合了ruby的语法,和erlang的OTP机制,目前正在自虐中(^o^)/~

设置rails中generator使用的orm类型

在最近的一个项目里, 同时使用了postgresql和mongoid,

结果在rails g model xxxx时, 默认调用的是mongoid,

虽然能通过--orm=actvie_record参数指定orm, 但还是很麻烦.

通过查询手册, 可以用下面的设置方式解决.

#config/application.rb

config.generators do |g|  
   g.orm             :active_record  
end

增加carrierwave对rails_admin的支持

由于rails_admin默认只是支持paperclip, 所以使用carrierwave的话, 需要手动做些修改.

一共3个文件

#app/views/rails_admin/main/_form_carrier_wave_file.html.haml

= label_tag "#{field.abstract_model.to_param}_#{field.name}", field.label
.input
  - if field.bindings[:object].send("#{field.name}_url")
    .row
      = link_to field.bindings[:object].send("#{field.name}_url")
      %br
      = form.check_box "remove_#{field.name}"
      = form.label "remove_#{field.name}", "Remove existing #{field.label.downcase}", :class => "inline"
  .row
    = form.file_field field.name, :class => "fileUploadField #{field.has_errors? ? "errorField" : nil}"
    = form.hidden_field "#{field.name}_cache"
#app/views/rails_admin/main/_form_carrier_wave_image.html.haml


= label_tag "#{field.abstract_model.to_param}_#{field.name}", field.label
.input
  - image = field.bindings[:object].send(field.name)
  - if image.path # the most direct check of an assets existence I could see

    .row
      -# load a default 'version' if it exists. should really be set through rails_admin's DSL:

      - default_version = image.versions[:main]
      = image_tag default_version && default_version.url || image.url
      %br
      = form.check_box "remove_#{field.name}"
      = form.label "remove_#{field.name}", "Remove existing #{field.label.downcase}", :class => "inline"
  .row
    = form.file_field field.name, :class => "fileUploadField #{field.has_errors? ? "errorField" : nil}"
    = form.hidden_field "#{field.name}_cache"
#config/initializers/rails_admin.rb


# Register a custom field factory and field type for CarrierWave if its defined

if defined?(::CarrierWave)
  module RailsAdmin::Config::Fields::Types
    # Field type that supports CarrierWave file uploads

    class CarrierWaveFile < RailsAdmin::Config::Fields::Types::FileUpload
      register_instance_option(:partial) do
        :form_carrier_wave_file
      end
    end
    
    # Field type that supports CarrierWave file uploads with image preview

    class CarrierWaveImage < CarrierWaveFile
      register_instance_option(:partial) do
        :form_carrier_wave_image
      end
    end
    
    # Register field type to the types registry

    register(:carrier_wave_file, CarrierWaveFile)
    register(:carrier_wave_image, CarrierWaveImage)
  end
  RailsAdmin::Config::Fields.register_factory do |parent, properties, fields|
    model = parent.abstract_model.model
    if model.kind_of?(CarrierWave::Mount) && model.uploaders.include?(properties[:name])
      type = properties[:name] =~ /image|picture|thumb/ ? :carrier_wave_image : :carrier_wave_file
      fields << RailsAdmin::Config::Fields::Types.load(type).new(parent, properties[:name], properties)
      true
    else
      false
    end
  end
end

rails调试插件rails-footnotes使用说明

说明

rails-footnotes 是一个在development环境下调试rails用的插件, 可以在当前页面的页脚处显示当前的调试信息,如session、实例变量、数据库查询时间等等

安装方式

#编辑Gemfile, rails3版本必须用rails-footnotes 3.7 版以上的版本

gem 'rails-footnotes', '>= 3.7', :group => 'development' 

bundle install

#编辑config/initializers/footnotes.rb

if defined?(Footnotes) && Rails.env.development?
    Footnotes.run! # first of all


    # ... other init code

end

注意

rails-footnotes默认使用textmate来编辑当前页面文件, 如果要自定义配置编辑器, 请看rails-footnotes文档

rails3rc1在安装rspec-rails时碰到报错

今天在rails3rc1下安装rspec-rails, 提示了以下错误

Invalid gemspec in [/Users/ZoOL/.rvm/gems/ruby-1.8.7-p334/specifications/rspec-core-2.6.2.gemspec]: invalid date format in specification: "2011-05-21 00:00:00.000000000Z"

解决方法

找到specifications/rspec-core-2.6.2.gemspec, 将下面这行注释

s.date = %q{2011-05-21 00:00:00.000000000Z}

另外在执行rake命令时, 遇到了下面的报错信息

undefined method `prerequisites' for nil:NilClass

google后发现是rspec-rails版本的问题, 使用2.6.1.beta1版本以上就好了, 编辑Gemfile

  gem 'rspec-rails', '~> 2.6.1.beta'

设置link标签使浏览器自动发现rss标签

<link rel="alternate" type="application/atom" title="ZoOL =&gt; Blog" href="http://zool.me/atom.xml" /> 

上述语句使得浏览器在打开我的博客时,会自动获取blog的rss地址。

另一个rss+xml格式

<link rel="alternate" type="application/rss+xml" title="ZoOL =&gt; Blog" href="http://blog.zool.it/feed.rss" /