每天一剂Rails良药之In-Place Form Editing

看看蛙眼的博客分类管理,有点In Place Editing的意思,是否让用户感觉更方便呢?
Rails有许多很小的好处,让人欲罢不能。
今天来看看Rails使用script.aculo.us让In Place Editing更简单,让你的应用更加Web2.0

1,新建Rails项目,配好数据库设置
[code]
rails test
[/code]

2,添加contacts表
[code]
ruby script/generate migration AddContactsTable
[/code]
然后修改001_add_contacts_table.rb:
[code]
class AddContactsTable < ActiveRecord::Migration
def self.up
create_table :contacts do |t|
t.column :name, :string
t.column :email, :string
t.column :phone, :string
t.column :address_line1, :string
t.column :address_line2, :string
t.column :city, :string
t.column :state, :string
t.column :country, :string
t.column :postal_code, :string
end
end

def self.down
drop_table :contacts
end
end
[/code]
然后运行rake:
[code]
rake db:migrate
[/code]

3,生成Contact的scaffold
[code]
ruby script/generate scaffold Contact
[/code]

4,添加默认的javascript库
修改app/views/layouts/contacts.rhtml,添加以下代码:
[code]
<%= javascript_include_tag :defaults %>
[/code]

5,添加In Place Editing效果
修改app/views/contacts/show.rhtml
[code]
<% for column in Contact.content_columns %>
<p>
<b><%= column.human_name %>:</b>
<%= in_place_editor_field :contact, column.name %>
</p>
<% end %>

<%= link_to 'Back', :action => 'list' %>
[/code]
注意<%= in_place_editor_field :contact, column.name %>这行代码就可以添加In Place
Editing效果,添加一个Contact并查看Show页面,实际上生成一段Javascript代码:
[code]
new Ajax.InPlaceEditor(....)
[/code]
这里是对Contact所有的字段作In Place Editing,我们也可以只指定某一个字段,如:
[code]
<%= in_place_editor_field :contact, :name %>
[/code]
但是现在还不能编辑字段,因为ContactsController没有相应的set_contact_attr()方法
还好Rails有相应的Convention来节省代码,在ContactsController里添加以下代码:
[code]
Contact.content_columns.each do |column|
in_place_edit_for :contact, column.name
end
[/code]
这样自动为每个字段生成set_contact_attr()方法了,现在访问页面看看效果吧!

6,更改InPlaceEditor的输入框的样式
参考[url=http://api.rubyonrails.com/]Rails Framework Documentation[/url]的方法API即可
例如这里我们可以让输入框改为5行15列的textarea:
[code]
<% for column in Contact.content_columns %>
<p>
<b><%= column.human_name %>:</b>
<%= in_place_editor_field :contact, column.name, {}, {:rows => 5, :cols => 15} %>
</p>
<% end %>

<%= link_to 'Back', :action => 'list' %>
[/code]
或者我们直接更改CSS做更细节上的修改:
[code]
.inplaceeditor-form input[type="text"] {
width: 260px;
}
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值