« 2011年10月的文章归档

修改validation中错误信息的字段名

在rails的activerecord中,如果对字段进行验证,出错信息中,往往会把表中的字段名显示成主语,比如:

class Person < ActiveRecord::Base
  validates :name, :presence => true
end

出错时显示的是:”Name can’t be blank”,其中”can’t be blank”是rails默认的信息,我们可以通过候改I18n,轻易的改成中文,但在以前的rails版本中,想把字段名(这里是name)友好化,那很麻烦。
不过现在也可以通过修改I18n配置文件来自定义你的字段描述了:

cn:
  activerecord:
    attributes:
      person:
        name: "姓名"

是不是很简单呢,嘎嘎。

修改form_for生成的提交按钮文字

  <%= form_for @post do |f| %>
    <%= f.submit %>
  <% end %>

这段代码会生成一个表单,而提交按钮默认值是英文,根据你的模型生成新增或更新字样,比如在上面这个例子中,如果@post是新记录,它将用”Creat Post”,如果不是新记录,会生成”Update post”字样。
这些值能通过I18n自定义,在helpers.submit键中允许使用 %{model} 做为翻译引用表单使用的模型名字:

  en:
    helpers:
      submit:
        create: "Create a %{model}"
        update: "Confirm changes to %{model}"
      post:
        create: "Add %{model}"

所以当我们使用中文时候可以建一个cn.yml

  cn:
    helpers:
      submit:
        create: "新建"
        update: "修改"
      post:
        create: "添加"

ExecJS::RuntimeUnavailable

好吧,这个错误我碰了好几次了。记录一下吧。
修改Gemfile,加上:
gem ‘execjs’
gem ‘therubyracer’

出错原因:

It does not show that it is running Ruby 1.9.1. Because the standard library changed very little between 1.9.1 and 1.9.2, the same path is used for both of them. You will notice this is not just on Heroku.

It looks like execjs is expecting to have a JS runtime installed on the system. Apparently Celadon Cedar does have one (NodeJS), but it won’t work until rails 3.1rc5 arrives.

gem 安装不了 rails

WARNING:  RubyGems 1.2+ index not found for

当出现以上错误时,有几种原因,网速过慢、gem服务器太慢、被墙了。
解决方案有几种,一种是自己一个一个下载gem包,本地安装,不过太麻烦。
另一种是修改源地址:
先查看一下当前源地址

gem env
gem sources list

一般默认是:http://rubygems.org/
增加几个源路径:

sudo gem sources -a http://gems.rubyforge.org
sudo gem sources -a http://gems.github.com

问题应该解决了。关于gem sources的用法可以看帮助:gem help sources