#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

你可能感兴趣的:(xml,Blog)