2011-03-28 34 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

感謝您的響應,但不知道這是如何解決更新方案?如果帳單記錄已存在,則不會被新值覆蓋。 – 2011-03-28 10:46:57

+0

好的 - 調整爲在同一路線上更新。然而,現在看起來有點冗長。 – stef 2011-03-28 11:01:29

+0

感謝您的想法。這讓我嘗試了更多的想法。我相信它不可變的原因是因爲我從用戶類和直接從帳單類引用相同的對象。因爲我很早就對用戶類進行了修改,所以它有效地阻止了我通過其他路由修改同一個對象 - 賬單地址類。仍然感到驚訝的是,在Ruby中沒有一個整潔的內膽可以做到這一點! – 2011-03-29 14:17:02