#95 More on ActiveResource

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章