Show Last modified tables/records Rails 3.2

2019-09-04 11:49发布

问题:

I still can't figure out how to implement this as i am a newbie with this. some people helpt me and said i had to use audited, so it did. this is my controller:

  def show

    add_breadcrumb 'Contract Bekijken', :contracten_path

    @contracten = Contracten.find(params[:id])

    @audits = @contracten.audits.collect { |a| a.created_at }

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @contracten }
    end
  end

Here's a pastie of my whole controller. http://pastie.org/4270702

But i don't know if this is right or how to implement this to my views.

I hope someone really can help because i really need this to work this week.

Thanks.


i have a rails app where i can store contracts in a database, it also has persons and factories tables in the database. Now i would like to have a last modified table.

I would like when people update/add a new record to the database, that it will show the modifications in the div right on the screenshot.

Thanks :D

回答1:

What you need is a audit history of edits.

You can either implement that yourself (may make sense if there is custom business logic involved you really want to write yourself) by hooking into the ActiveRecord callbacks for that model.

A sample implementation may look like this:

class Contract < ActiveRecord::Base
  after_save :audit

  def audit
    log = AuditLog.new(:user_id => current_user, :action => :update, ...)
    log.save
  end
end

This would assume you have a AuditLog Model that contains the appropriate fields you want to log to and in your audit method you write to that.

Or, a simpler way is to use the Audited gem that does that for you (but may come with some limitations).

From the documentation of Audited it seems like you can simply fetch a Contract record and use the audits on that model to then access the audited information.

Sample

def show
  @contract = Contract.find(params[:id])
  @audits = @contract.audits.collect { |a| a.created_at }
end

Now you have all the timestamps of the audits in the @audits variable and can access them from the view using <% @audits.each do ....



回答2:

From your question it seems like you just need a list based on the updated_at field.

How about - @contract_list = Contract.all.order( "updated_at DESC").limit(10)

Then you can iterate over the list in the view.

Nice looking page!