【问题标题】:Datamapper "Update" does not update recordDatamapper“更新”不更新记录
【发布时间】:2012-04-14 12:10:46
【问题描述】:

我遇到了 datamapper 不更新模型的问题。我可以毫无问题地创建和保存模型。我启用了raise_on_save_failure 并检查了update 的返回值,但没有看到任何错误。

这是模型:

class UserProfile   
  include DataMapper::Resource  
  attr_accessor :id, :wants_hints, :is_beta_user  
  property :id, Serial #auto-increment integer key  
  property :is_beta_user, Boolean  
  property :wants_hints, Boolean  
  has 1, :user, :through => Resource 
end 

这是在控制器中更新的地方:

if user = User.get(request.session[:user])      
  if request.params[:user_profile]        
    beta = request.params[:user_profile].has_key?('is_beta_user')        
    hints = request.params[:user_profile].has_key?('wants_hints')        
    user.user_profile.update({:is_beta_user => beta, :wants_hints => hints}) # returns true
    Log.puts user.user_profile.errors.each {|e| Log.puts e.to_s} # returns empty list []
  end    
end

当控制器被调用时update总是返回true,并且错误列表中永远不会有错误。设置为:debug 的数据映射器日志仅显示用于检索useruser_profileSELECT 查询,仅此而已。为什么我可以save 一个新创建的模型,但不允许update 相同的模型?

【问题讨论】:

    标签: ruby datamapper


    【解决方案1】:

    删除attr_accessor 解决了这个问题。根据我的研究,attr_accessor 用于不在数据库中的属性。

    【讨论】:

      【解决方案2】:

      DataMapper 的saveupdate 不一定会产生UPDATE 语句。只有当模型对象持有的数据发生变化时,它才会这样做。因此,例如,在以下代码中,update 将返回 true,但不会产生 UPDATE

      # This generates an INSERT
      user = User.create(:login => 'kintaro', :email => 'kintaro@example.com')
      
      # This does NOT generate an UPDATE
      user.update(:login => 'kintaro')
      

      但是,如果您这样做,则会生成 UPDATE

      # This generates an UPDATE
      user.update(:login => 'kintaro22')
      

      也许这就是正在发生的事情?

      【讨论】:

      • 检查并仔细检查。它肯定是在将属性更新为新值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2020-05-30
      • 2017-11-25
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多