我有一个用户类,可以选择使用帐单邮寄地址。当我发布付款表单时,假设用户已表明他们想要保存他们的帐单邮寄地址详细信息,我想要创建新的地址记录或更新原始地址记录。
我尝试了很多东西,但我能找到最接近工作代码的是......
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 = !!@post["remember"]
if user.remember_billing
user.billing_address = BillingAddress.first_or_create({ :user => user }, @addr)
end
user.save
...
在没有记录时工作正常。但如果已有记录,它会保留原始值。
我看到了类似的帖子 DataMapper: Create new record or update existing 但如果我改变代码
user.billing_address = BillingAddress.first_or_create(:user => user).update(@addr)
我收到错误
DataMapper::ImmutableError at /pay
Immutable resource cannot be modified
任何帮助非常感谢
答案 0 :(得分: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