---
title: "Rails 常用代码"
author: "RobinWu"
date: "2011-10-25T16:32:29Z"
tags: []
categories: ["编程语言"]
slug: "rails"
draft: false
lastmod: "2013-05-30T11:24:40Z"
id: 1213908
url: "https://robinwu.iteye.com/blog/1213908"
---

paperclip default_url by assets

```java
 has_attached_file :photo, :styles => { :thumb => "100x100>" }, :default_url => ActionController::Base.helpers.asset_path('recipe_missing.jpg')
```


指定rails 版本 new

```java

rails _2.3.4_ test_ar_base

```


to_json

```java

  ActiveRecord::Base.include_root_in_json = true
 konata.to_json(:methods => :permalink)
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true,
        "permalink": "1-konata-izumi"}

```



rails g

```java

rails g scaffold xxx --view-specs=false --routing-specs=false --stylesheets=false

```


正则表达式 * 不贪婪

```java

.*?

```


update file

```java

      Dir.glob(File.join(Rails.root, Wms::ENV, 'xpages', '*.json')) do |json_file|
        rf = File.new(json_file, 'r')
        new_cont = convert_u8_to_zh(rf.read)
        rf.close

        wf = File.new(json_file, 'w')
        wf.write new_cont
        wf.close
      end

```



Rails console tip

> 
> http://37signals.com/svn/posts/3176-three-quick-rails-console-tips
> http://api.rubyonrails.org/classes/Rails/ConsoleMethods.html
> 


```java

app.class #=> ActionDispatch::Integration::Session
app.project_path(Project.first)
app.get("projects/1.atom") #=> 200
app.response.body #=> "<?xml ..."

helper.link_to 'Home', app.root_path

```


Tail number 0

 def strip_tail_zero(number)
    number = number.to_s
    if number =~ /\./
      number = number.gsub(/0+$/, "")
    end
    number.gsub(/\.$/, "")
  end