See how to handle authentication and custom actions using ActiveResource in this episode.
# models/product.rb (in blog app)
class Product < ActiveResource::Base
self.site = "http://admin:secret@localhost:3000"
end
# script/console (in blog app)
Product.find(:all) # GET products.xml
Product.find(:all, :params => { :search => 'table' }) # GET products.xml?search=table
p = Product.create(:name => 'foo') # POST products.xml
p.name = 'bar'
p.save # PUT products/11.xml
p.destroy # DELETE products/11.xml
Product.get(:recent) # GET products/recent.xml
p = Product.find(1) # GET products/1.xml
p.put(:discontinue) # PUT products/1/discontinue.xml
# routes.rb (in store app)
map.resources :products, :collection => { :recent => :get },
:member => { :discontinue => :put }
# products_controller.rb (in store app)
before_filter :authorize
protected
def authorize
authenticate_or_request_with_http_basic do |username, password|
username == "admin" && password == "secret"
end
end
本文介绍如何使用ActiveResource处理身份验证及自定义操作,演示了产品模型的CRUD操作,并展示了如何通过路由实现特定资源请求。

被折叠的 条评论
为什么被折叠?



