1

I am having trouble with datamapper not updating a model. I can create and save models without issue. I have enabled raise_on_save_failure and checked the return value of update but see no errors.

Here is the model:

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 

And here is where it is updated in the controller:

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

When the controller is called update always returns true, and there are never errors in the error list. The datamapper log, which is set to :debug, only shows the SELECT queries for retrieving the user and user_profile and that is all. Why would I be able to save a newly created model, but not be allowed to update that same model?

4

2 回答 2

2

Removing attr_accessor fixed the problem. From my research attr_accessor is used for attributes not in the database.

于 2012-04-14T03:50:57.027 回答
1

DataMapper's save and update do not necessarily produce an UPDATE sentence. It will only do so if the data held by the model object has changed. So, for example, in the following code the update will return true but will not produce an UPDATE:

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

# This does NOT generate an UPDATE
user.update(:login => 'kintaro')

If you do this, however, an UPDATE will be produced:

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

Maybe this is what's happening?

于 2012-04-13T17:46:23.267 回答