سؤال

I'm trying to add ordering/re-ordering to a resource in Active Admin. I understand that you can sort by the different columns for viewing while logged in. What I'd like to do is be able to order items so they display in a specific order on the front end. Any ideas on how to accomplish this?

I have a sort column in the database already.

Also I'd like to display the items in that specific order on in the admin section.

Anyone have any ideas on how I'd accomplish this?

هل كانت مفيدة؟

المحلول

I implemented this recently using a column called position on my HomeSlide model.

ActiveAdmin.register HomeSlide do
  config.sort_order = 'position_asc'

  index do
    column :title
    default_actions
  end

  # This action is called by javascript when you drag and drop a column
  # It iterates through the collection and sets the new position based on the
  # order that jQuery submitted them
  collection_action :sort, :method => :post do
    params[:home_slide].each_with_index do |id, index|
      HomeSlide.update_all(['position=?', index+1], ['id=?', id])
    end
    render :nothing => true
  end

end

Add this to your active_admin javascripts (coffee script)

sendSortRequestOfModel = (model_name) ->
  formData = $('#' + model_name + ' tbody').sortable('serialize')
  formData += "&" + $('meta[name=csrf-param]').attr("content") + "=" + encodeURIComponent($('meta[name=csrf-token]').attr("content"))
  $.ajax
    type: 'post'
    data: formData
    dataType: 'script'
    url: '/admin/' + model_name + '/sort'

jQuery ($) ->

  # home page slides
  if $('body.admin_home_slides.index').length
    $( "#home_slides tbody" ).disableSelection()
    $( "#home_slides tbody" ).sortable
      axis: 'y'
      cursor: 'move'
      update: (event, ui) ->
        sendSortRequestOfModel("home_slides")

نصائح أخرى

Do you have a separate frontend controller then? For the activeadmin part of your question:

It is possible to have a

config.sort_order = 'lastname_asc'

or

config.sort_order = 'created_at_desc'

declaration inside the ActiveAdmin.register block of your model / resource.

In your model, you could put something like

default_scope :order => "id DESC"

Reading your question though it seems appropriate for you to read some documentation, Here is a part copied from http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html

class Article < ActiveRecord::Base
  scope :published, where(:published => true)
  scope :featured, where(:featured => true)

  def self.latest_article
    order('published_at desc').first
  end

  def self.titles
    map(&:title)
  end

end

Which allows you to call the methods like this:

Article.published.featured.latest_article
Article.featured.titles

Good luck.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top