background: I am building a web app using Sinatra
and ActiveRecord
and I am keen to take advantage of acts_as_audited
(as per https://github.com/collectiveidea/acts_as_audited). The docs for acts_as_audited
assume I'll be using Rails
and so assume I'll use Rails
to generate the necessary migrations. I've not found any examples of using acts_as_audited
with Sinatra
.
So my question: Can someone point me at an example of using Sinatra
and ActiveRecord
with acts_as_audited
?
I have been able to get this to work using the Audit.as_user method. Using this method lets you audit records as if the change were made by the user object you pass in.
Here is a simple example.
# This is my User model, I want to audit email address changes to it.
class User < ActiveRecord::Base
acts_as_audited
# user has :email attribute
...
end
# This is what I would call in my Sinatra code.
# user is an instance of my User class
...
Audit.as_user(user) do
user.audit_comment = "updating email from sinatra"
user.update_attribute(:email, 'foo@bar.com')
end
...
A more complex example...
# Now I have a User model and a Comments model and I
# want to audit when I create a comment from Sinatra
class User < ActiveRecord::Base
has_many :comments
acts_as_audited
...
end
class Comment < ActiveRecord::Base
belongs_to :user
acts_as_audited
# has a :body attribute
...
end
# This is what I would call in my Sinatra code.
# Again, user is an instance of my User class
...
Audit.as_user(user) do
user.comments.create(
:body => "Body of Comment",
:audit_comment => "Creating Comment from Sinatra"
)
end