2011-03-28 1 views
0

청구서 수신 주소를 선택적으로 가질 수있는 사용자 클래스가 있습니다. 결제 양식을 게시 할 때 사용자가 청구서 수신 주소 정보를 저장하겠다고 표시했다고 가정하면 새 주소록을 만들거나 원래 주소록을 업데이트하려고합니다.Ruby/Datamapper가 생성 또는 업데이트 문제 - 불변 오류

나는 많은 것들을 시도했지만 내가 코드를 작업에 얻을 수있는 가장 가까운 ... 어떤 기록이없는 경우 잘 작동

class User 
    include DataMapper::Resource 
    property :id,   Serial 
    property :provider, String, :length => 100 
    property :identifier, String, :length => 100 
    property :username, String, :length => 100 
    property :remember_billing, Boolean 
    has 1, :billing_address 
end 

class BillingAddress 
    include DataMapper::Resource 
    property :first,  String, :length => 20 
    property :surname,  String, :length => 20 
    property :address1, String, :length => 50 
    property :address2, String, :length => 50 
    property :towncity, String, :length => 40 
    property :state,  String, :length => 2 
    property :postcode, String, :length => 20 
    property :country,  String, :length => 2 
    property :deleted_at, ParanoidDateTime 
    belongs_to :user, :key => true 
end 

post "/pay" do 
    @post = params[:post] 
    @addr = params[:addr] 
    if @addr == nil 
    @addr = Hash.new 
    end 

    user = User.first(:identifier => session["vya.user"]) 
    user.remember_billing = [email protected]["remember"] 

    if user.remember_billing 
    user.billing_address = BillingAddress.first_or_create({ :user => user }, @addr) 
    end 
    user.save 
    ... 

입니다. 그러나 이미 레코드가 있으면 원래 값을 유지합니다.

나는 비슷한 포스트 을 보았다하지만 난 코드를 변경하는 경우

user.billing_address = BillingAddress.first_or_create(:user => user).update(@addr) 

내가 오류를 얻을 수

DataMapper::ImmutableError at /pay 
Immutable resource cannot be modified 

많은

답변

0

당신은 체인있어 감사 어떤 도움 함께 많은 것들이 있습니다. 방법 :

billing = BillingAddress.first_or_new(:user => user, @addr) #don't update, send the hash as second parameter 
billing.saved? ? billing.update(@addr) : billing.save 
raise "Billing is not saved for some reason: #{billing.errors.inspect}" unless billing && billing.saved? 
user.billing_address = billing 
user.save 
+0

응답 해 주셔서 감사합니다. 그러나 이것이 어떻게 업데이트 시나리오를 해결할 수 있는지 잘 모르십니까? 결제 기록이 이미있는 경우 새 값으로 덮어 쓰지 않습니다. –

+0

확인 - 같은 경로에서 업데이트가 가능하도록 조정되었습니다. 그러나 지금은 조금 자세하게보고 있습니다. – stef

+0

아이디어에 감사드립니다. 이것은 나에게 몇 가지 아이디어를 더 시험해 보도록했다. 사용자 클래스와 청구서 클래스에서 동일한 객체를 참조하기 때문에 불변의 이유가 있다고 생각합니다. 내가 초기에 사용자 클래스를 변경했기 때문에 다른 경로 (청구서 수신 주소 클래스)를 통해 동일한 개체를 수정하지 못하게되었습니다. 루비에서 이것을 할 수있는 깔끔한 라이너가 아직 없다는 것에 놀랐습니다! –