2010-06-01 6 views
0

GEM을 통해 API를 사용하여 Google 회계 패키지 (FreeAgentCentral)를 사용하여 게시 된 정보를 얻으려고합니다.REST API 도움말 (레일)

http://github.com/aaronrussell/freeagent_api/ 

나는 (아마도) 작업을 얻을 수있는 다음과 같은 코드가 있습니다

카세 컨트롤러

def create 
    @kase = Kase.new(params[:kase]) 
    @company = Company.find(params[:kase][:company_id]) 
    @kase = @company.kases.create!(params[:kase]) 

    respond_to do |format| 
     if @kase.save 
     UserMailer.deliver_makeakase("[email protected]", "Highrise", @kase) 
     @kase.create_freeagent_project(current_user) 

     #flash[:notice] = 'Case was successfully created.' 
     flash[:notice] = fading_flash_message("Case was successfully created & sent to Highrise.", 5) 

     format.html { redirect_to(@kase) } 
     format.xml { render :xml => @kase, :status => :created, :location => @kase } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @kase.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

을 저장하려면를 통해 찾고, 중요한 부분은 다음과 같습니다

@kase.create_freeagent_project(current_user) 

가세 모델

# FreeAgent API Project Create 
    # Required attribues 
    # :contact_id 
    # :name 
    # :payment_term_in_days 
    # :billing_basis     # must be 1, 7, 7.5, or 8 
    # :budget_units      # must be Hours, Days, or Monetary 
    # :status       # must be Active or Completed 
    def create_freeagent_project(current_user) 
    p = Freeagent::Project.create(
     :contact_id    => 0, 
     :name     => "#{jobno} - #{highrisesubject}", 
     :payment_terms_in_days => 5, 
     :billing_basis   => 1, 
     :budget_units   => 'Hours', 
     :status     => 'Active' 
    ) 
    user = Freeagent::User.find_by_email(current_user.email) 
    Freeagent::Timeslip.create(
     :project_id => p.id, 
     :user_id => user.id, 
     :hours => 1, 
     :new_task => 'Setup', 
     :dated_on => Time.now 
    ) 
    end 

lib 디렉토리/freeagent_api.rb

require 'rubygems' 
gem 'activeresource', '< 3.0.0.beta1' 
require 'active_resource' 

module Freeagent 

    class << self 
    def authenticate(options) 
     Base.authenticate(options) 
    end 
    end 

    class Error < StandardError; end 

    class Base < ActiveResource::Base 
    def self.authenticate(options) 
     self.site = "https://#{options[:domain]}" 
     self.user = options[:username] 
     self.password = options[:password] 
    end 
    end 

    # Company 

    class Company 
    def self.invoice_timeline 
     InvoiceTimeline.find :all, :from => '/company/invoice_timeline.xml' 
    end 
    def self.tax_timeline 
     TaxTimeline.find :all, :from => '/company/tax_timeline.xml' 
    end 
    end 
    class InvoiceTimeline < Base 
    self.prefix = '/company/' 
    end 
    class TaxTimeline < Base 
    self.prefix = '/company/' 
    end 

    # Contacts 

    class Contact < Base 
    end 

    # Projects 

    class Project < Base 

    def invoices 
     Invoice.find :all, :from => "/projects/#{id}/invoices.xml" 
    end 

    def timeslips 
     Timeslip.find :all, :from => "/projects/#{id}/timeslips.xml" 
    end 

    end 

    # Tasks - Complete 

    class Task < Base 
    self.prefix = '/projects/:project_id/'   
    end 

    # Invoices - Complete 

    class Invoice < Base 

    def mark_as_draft 
     connection.put("/invoices/#{id}/mark_as_draft.xml", encode, self.class.headers).tap do |response| 
     load_attributes_from_response(response) 
     end 
    end 
    def mark_as_sent 
     connection.put("/invoices/#{id}/mark_as_sent.xml", encode, self.class.headers).tap do |response| 
     load_attributes_from_response(response) 
     end 
    end 
    def mark_as_cancelled 
     connection.put("/invoices/#{id}/mark_as_cancelled.xml", encode, self.class.headers).tap do |response| 
     load_attributes_from_response(response) 
     end 
    end 

    end 

    # Invoice items - Complete 

    class InvoiceItem < Base 
    self.prefix = '/invoices/:invoice_id/' 
    end 

    # Timeslips 

    class Timeslip < Base 

    def self.find(*arguments) 
     scope = arguments.slice!(0) 
     options = arguments.slice!(0) || {} 
     if options[:params] && options[:params][:from] && options[:params][:to] 
     options[:params][:view] = options[:params][:from]+'_'+options[:params][:to] 
     options[:params].delete(:from) 
     options[:params].delete(:to) 
     end 

     case scope 
     when :all then find_every(options) 
     when :first then find_every(options).first 
     when :last then find_every(options).last 
     when :one then find_one(options) 
     else    find_single(scope, options) 
     end 
    end  
    end 

    # Users 

    class User < Base 
    self.prefix = '/company/' 
    def self.find_by_email(email) 
     users = User.find :all 
     users.each do |u| 
     u.email == email ? (return u) : next 
     end 
     raise Error, "No user matches that email!" 
    end 
    end 

end 

설정/초기화/freeagent.rb

Freeagent.authenticate({ 
    :domain => 'XXXXX.freeagentcentral.com', 
    :username => '[email protected]', 
    :password => 'XXXXXX' 
    }) 

위의 새를 만들려고 할 때 다음과 같은 오류 렌더링 케이스를보고 FreeAgent에게 세부 사항을 보내십시오 :

누군가가이 문제에 어떤 빛을 흘릴 수 있다면 17,451,515,
ActiveResource::ResourceNotFound in KasesController#create 

Failed with 404 Not Found 

ActiveResource::ResourceNotFound (Failed with 404 Not Found): 
    app/models/kase.rb:56:in `create_freeagent_project' 
    app/controllers/kases_controller.rb:96:in `create' 
    app/controllers/kases_controller.rb:93:in `create' 

Rendered rescues/_trace (176.5ms) 
Rendered rescues/_request_and_response (1.1ms) 
Rendering rescues/layout (internal_server_error) 

주시면 감사하겠습니다!

감사합니다,

대니

답변

1

어떻게 만들 호출? 정상적인 안정된 동작으로 폼이나 다른 것으로부터의 POST가있을 것입니다. 그러나 404는 일반적으로 실패한 GET 액션에서 렌더링됩니다. ActiveRecord 찾기는 특정 ID로 레코드를 찾지 못합니다. 내 추측은 당신이 GET으로 만들 호출하고 있으며, 줄 것을

user = Freeagent::User.find_by_email(current_user.email) 

단순히 이메일로 사용자를 찾을 수없는, 그래서 ResourceNotFound 예외를 던지고 있다는 점이다.

또한, 코드의이 비트는 나에게 혼란 :

@kase = Kase.new(params[:kase]) 
@company = Company.find(params[:kase][:company_id]) 
@kase = @company.kases.create!(params[:kase]) 

respond_to do |format| 
    if @kase.save 

왜 kases.create 한 번 Kase.new에 한 번, 두 번 여기 @kase 만드는? 또한, 라인 참고 :

if @kase.save 

이 항상 true 평가합니다

라인 때문에 : 그것은 그 @kase을 말하는 또 다른 방법이다, 거짓 인 경우

@company.kases.create!(params[:kase]) 

가 예외를 던진 것이다. 만들기 때문에 중복 저장됩니다! 새로운 Kase 레코드를 이미 유지했을 것입니다.

편집 :

# this line can go @kase = Kase.new(params[:kase]) 
@company = Company.find(params[:kase][:company_id]) 
@kase = @company.kases.build(params[:kase]) 

편집 : 나는 당신이 있었다 할 의미 어떻게 생각 당신은 아마 원하는이 같은 새로운 액션 :

def new 
    @kase = Kase.new # no params here 
end 

'새'ERB 템플릿이 form_for이있을 것이다 같은 모양 :

등 그 양식은 기본적으로 폼에서 작성 작업에 매개 변수를 게시 할 것입니다 당신은 자원과 같은 것을 설정했습니다 : 당신의 경로에 kase. 그것은 당신을 시작해야합니다. 당신이하는 것처럼 표준 자습서를 따르십시오.

+0

현재 사용자의 전자 메일 주소가 무료 에이전트 전자 메일 주소와 일치하는지 이중/삼중으로 확인했습니다. ResourceNotFound 예외에 대한 다른 이유가 있습니까? kase에 관한 두 번째 의견을 작성해야합니다. 귀하의 의견대로 생각합니다! 감사합니다, 나는 그 ResourceNotFound를 던질 수있는 볼 수있는 유일한 라인의 대니 – dannymcc

+0

. 실패한 찾기를 일으키는 일부 공백이있을 수 있습니까? find_by_email 바로 뒤에 출력을 추가하여 사용자를 찾고 있는지 확인하십시오. 그런 다음 서버 출력을 확인하여 확인하십시오. –

+0

할거야. 감사! – dannymcc