Dust Of Dream

知识真的是一个圆么?

Agile Web Development with Rails 3nd Edition 阅读笔记

Agile Web Development with Rails 3nd Edition 阅读笔记
1.session 使用
1)如何使用数据库保存session,以增加session的安全性?
  > rake db:sessions:create 创建Session相关的表结构
  > rake db:migrate 在数据库中创建表
  修改 environment.rb 中使用database来代替默认采用基于cookie的存储方式.
  # Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create')
config.action_controller.session_store = :active_record_store
然后在基类application.rb中加入
session :session_key => '_session_id' #(存入cookie的ID)
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => '8c3e099237e6366fd2f5366e9c430e79' #(加密字符串,换个自己的吧)
简单一个session应用实例(找下session是否存在cart,不存在就创建一个新的扔进去)
def find_cart
unless session[:cart]
session[:cart] = Cart.new 
end
session[:cart]
end
上面乱七八糟的代码可以简写成 session[:cart] ||= Cart.new
2.使用<%= render(:partial => "cart_item" , :collection => @cart.items) %>可以引入一个control,其中对应的control的文件名为"_cart_item.html.erb,在片段中引用的变量为"cart_item".在书中的实例如下:
depot/app/views/store/add_to_cart.html.erb
[CODE]
<div class="cart-title">Your Cart</div>
<table>
<%= render(:partial => "cart_item" , :collection => @cart.items) %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart" , :action => :empty_cart %>
[CODE]
[CODE]
depot/app/views/store/_cart_item.html.erb
<tr>
<td><%= cart_item.quantity %>&times;</td>
<td><%=h cart_item.title %></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
[CODE]
上面使用的是一个循环调用某个control,可以只传入一个Object
<%= render(:partial => "cart" , :object => @cart) %>
3.如何使用Ajax
  先使用<%= javascript_include_tag :defaults %> 引入默认的Javascript
  然后使用
  <% form_remote_tag :url => { :action => :add_to_cart, :id => product } do %>
<%= submit_tag "Add to Cart" %>
<% end %>
使用ajax触发动作.
一个简单的Helper类里面定义方法的使用:
def hidden_div_if(condition, attributes = {}, &block)
if condition
attributes["style" ] = "display: none"
end
content_tag("div" , attributes, &block)
end
在页面上使用
<% hidden_div_if(@cart.items.empty?, :id => "cart" ) do %>
<%= render(:partial => "cart" , :object => @cart) %>
<% end %>
来引用.

posted on 2008-12-04 18:45 Anemone 阅读(322) 评论(0)  编辑  收藏 所属分类: RUBY学习


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

Blog Stats

News

常用链接

留言簿(1)

随笔分类

随笔档案

新闻档案

相册

常去网站

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜