[Rails] Re: Finding out updated fields

Jean-François jf.web3 at gmail.com
Tue Apr 18 20:03:19 GMT 2006


Hello,

Lantis :
> It's not really what i want. That recipe shows how to keep track of
> user's activity. What i want is to find out what was changed in the edit
> operation (the fields of the record & the new .

Alain :
> [...] Since rails know the value of all fields (that is how it
> is able to auto-populate them), it should be aware of changes
> to any of these fields by comparing the
> params hash with the hash in memory.

Yes, I think that's the way we should do it, if Rails doesn't do it,
let's do it instead !

Assuming a Person model, here a typical scaffolded code...

  def edit
    @person = Person.find(params[:id])
  end

  def update
    @person = Person.find(params[:id])
    if @person.update_attributes(params[:person])
      flash[:notice] = 'Person was successfully updated.'
      redirect_to :action => 'show', :id => @person
    else
      render :action => 'edit'
    end
  end


So, the idea is to take the params[:person] hash and remove
the not-changing key/value pairs.


  def update
    @person = Person.find(params[:id])

    attr = @person.attributes
    new_attr = params[:person]
    new_attr.delete_if { |k,v| attr.has_key?(k) && attr[k] == v }

    # => updated fields in new_attr Hash
    # if we wanna display it, use a @new_attr variable.

    if @person.update_attributes(new_attr)
      flash[:notice] = 'Person was successfully updated.'
      redirect_to :action => 'show', :id => @person
    else
      render :action => 'edit'
    end
  end

No tested though, but it should do the trick.

So if it works, you can add a method to AR::B like that :

def update_only_changed_attributes(attrs)
  attrs.delete_if do|key,value|
     has_attribute?(key) && self[key] == value
  end
  update_attributes(attrs)
end

Not tested... again :)

In the debugging process of this method, i'm wondering if we
have to check for the primary key, to remove it from the hash or not.
And other issues i haven't suspected... (do i have to stringify the keys ?)

     -- Jean-François.


--
À la renverse.


More information about the Rails mailing list