---
title: "In-plcae-editing by Rails"
author: "thegiive"
date: "2007-02-09T09:15:57Z"
tags: ["Ajax", "JavaScript", "Rails", "Ruby", "生活"]
slug: "in-plcae-editing-by-rails"
draft: false
lastmod: "2007-02-09T09:15:57Z"
id: 53634
url: "https://thegiive.iteye.com/blog/53634"
---

[![](http://bp0.blogger.com/_8vS0KjIsbko/Rcw4a-LXumI/AAAAAAAAAFk/LElUtv67H10/s400/%E6%9C%AA%E5%91%BD%E5%90%8D.jpg)](http://bp0.blogger.com/_8vS0KjIsbko/Rcw4a-LXumI/AAAAAAAAAFk/LElUtv67H10/s1600-h/%E6%9C%AA%E5%91%BD%E5%90%8D.jpg)  
ㄜ，其實真的很難解釋什麼叫做 in-place-editing 這個 AJAX 效果，簡單講就是你可以直接編輯畫面上某些欄位，而不用進入專門編輯的頁面，上圖就是最典型的效果。

這個效果廣泛的使用在 Flickr 以及其他的 AJAX 網頁。由於太過方便，常用，所以 [script.aculo.us](http://script.aculo.us/) 就有這個效果，Rails 也對這個效果寫了相當方便的 [Javascript Helper](http://api.rubyonrails.com/classes/ActionView/Helpers/JavaScriptMacrosHelper.html#M000570)，並且做出一個相當完善的整合。雖然這個功能在 Rails 2.0 裡面即將被取消內建，轉為 plugin 形式，但是由於日常生活使用到的機會也蠻多的，我還是第一個 AJAX 效果就介紹這個。Ruby on Rails 上面要使用 in-place-editing 是相當相當方便的。一共有三步，我們假設我們想 in-place-editing abc model 裡面的 name column。

第一步：加入相關 Lib  
在 HTML head 裡面加入相關 Javascritp Lib

> javascript\_include\_tag :defaults

第二步：View  
在view 裡面，你需要 in-place-editing的位置，加入相關 in-place-editor 的 field

> in\_place\_editor\_field 'abc' , 'name'

第三步：Controller  
在你的 controller 裡面，加入 in-place-editor 的宣告

> class AbcController &lt; ApplicationController  
> in\_place\_edit\_for :abc , :name  
> end

沒錯，不多不少三步就好。沒有任何 Javascript 宣告，只有簡潔有力的 Rails Style Coding，很棒吧。

中文化

如果你想將裡面內建的 ok , cancel 改成中文的話，請在 view 裡面使用

> in\_place\_editor\_field 'abc' , 'name' , :save\_text =""&gt; '儲存' , :cancel\_text =&gt; '取消' , :loading\_text =&gt; '儲存中'

即可變成中文字。

多個 column in-place-editing

如果你想要一個 controller 有多個 in-place-editing 的 column，這裡就有點不方便了，可能必須要這樣寫

> class AbcController &lt; ApplicationController  
> in\_place\_edit\_for :abc , :name  
> in\_place\_edit\_for :abc , :nickname  
> end

**延伸閱讀**

- [JavaScript helper Manual](http://api.rubyonrails.com/classes/ActionView/Helpers/JavaScriptMacrosHelper.html#M000570)