Downloading all records of a paginated resource in ActiveAdmin - activeadmin

I am trying to use the collection action "download_csv" already present in Active Admin to download all the records of a resource. However, the action only downloads the contents of the present page. As I have paginated the resource, the data needs to be downloaded from all the pages. Any suggestions on how I can approach this problem ?

Just for future googlers. My fix (working for the current Master 1.0.0pre) is to add the following to config/initializers/active_admin.rb:
module ActiveAdmin
class ResourceController
module DataAccess
# needed for current active admin master
def max_per_page
30_000
end
def per_page
return 30_000 if %w(text/csv application/xml application/json).include?(request.format)
return max_per_page if active_admin_config.paginate == false
#per_page || active_admin_config.per_page
end
end
end
end
Replace the max as needed. This works for csv, xml and json downloads.

This answer might be a little late but hopefully it can help somebody.
Here is how I have this working in my current app:
csv do
ModelName::ATTR_ADMIN_EXPORT.each do |sym|
column sym
end
end
And in the model I have ATTR_ADMIN_EXPORT defined like this:
ATTR_ADMIN_EXPORT = [:name, :created_at]
Let me know if this works for you!

You could try this
before_filter :only => :index do
#per_page = 10 unless request.format == 'text/csv'
end
This code will also make the pagination dynamic.
before_filter :only => :index do
if params[:pag].blank?
#per_page = AdminSetting.where(:name => 'JobPagination').first.value.to_i unless request.format == 'text/csv'
else
#per_page = 10
end
end

Related

Active Admin create additional URL on unique field

I have an object Foo which has fields id and token (both are unique, both have db indexes). I want to be able to get to Foo 1 by going to url "/admin/foos/token-of-foo-1" in addition to being able to use the url "/admin/foos/1". I know that I will need to do something like the below in my routes.rb, but I'm having trouble. Help?
ActiveAdmin.routes(self) # keep this
get 'admin/???', to: 'admin/???' # add ...something
Hmm, some thoughts:
#admin/foo.rb
controller do
def find_resource
if params[:id].length == 16 # it's a token
end_of_association_chain.find_by_token(params[:id])
else
end_of_association_chain.find(params[:id])
end
end
end
For this kind of purposes I use this gem called FriendlyID. You can select which fields should form the URL slug, in your case the field token:
class Foo < ApplicationRecord
extend FriendlyId
friendly_id :token, use: :slugged
end
Let me know if you have more doubts on how to configure. It has a great integration with Active Admin.

cyber-duck/laravel-excel file corrupt / invalid format

I've spent hours finding out why the excel export with the package cyber-duck/laravel-excel export OK the excel when the datasource is a query, but when using a custom serialiser it simply stops formatting the excel correctly
No errors in code, super simple excel. Even trying the code posted in the documentation:
Usage:
$serialiser = new CustomSerialiser();
$excel = Exporter::make('Excel');
$excel->load($collection);
$excel->setSerialiser($serialiser);
return $excel->stream('filename.xlsx');
CustomSerialiser:
namespace App\Serialisers;
use Illuminate\Database\Eloquent\Model;
use Cyberduck\LaravelExcel\Contract\SerialiserInterface;
class ExampleSerialiser implements SerialiserInterface
{
public function getData($data)
{
$row = [];
$row[] = $data->field1;
$row[] = $data->relationship->field2;
return $row;
}
public function getHeaderRow()
{
return [
'Field 1',
'Field 2 (from a relationship)'
];
}
}
Any thoughts?
What software do you use to open the file? Excel? OpenOffice?
If you open the test folder > Unit > ExporterTest.php, you should see a working example in test_can_use_a_custom_serialiser.
You can change row 155 to $exporter = $this->app->make('cyber-duck/exporter')->make('Excel');, row 160 to $reader = ReaderFactory::create(Type::XLSX); (otherwise it would use a CSV) and comment out line 174 to keep the file so you can open it after the test has running.
The ExampleSerialiser you posted needs to be modified to match your Eloquent model and relationships. Also, the example use an Eloquent version and you mentioned the query builder. If you want to use the Query builder version, you need to use loadQuery (I'll try to update the documentation next week to cover this user case). Feel free to drop me an email with your code so I can have a look and try to help out (It's a bit hard to understand the issue without seeing the actual implementation). You should find me on github, I'm one of the Cyber-Duck guys working on our projects.

Is it possible to generate cucumber html reports with only scenario titles with out steps

Is it possible to generate cucumber html reports with only scenario titles with out steps?
I am looking to generate html report by email,But i want the reports to be generated with all scenarios only with title, so that my report is not huge and easy to know which scenarios failed.
I am sure somebody may have solution for this.Can ony one please share this or give me idea how would i get it done.
Thanks in advance
You would need to build a custom formatter. The Cucumber Wiki has some details on doing this.
To hide the steps, you can create a custom formatter that overrides the Html formatter's before_step_result and build_step methods.
If your support folder create an .rb file with:
require 'cucumber/formatter/html'
module Cucumber
module Formatter
class HtmlStepless < Html
def before_step_result(step_result)
#TODO: What is this used for?
#step_match = step_result.step_match
#hide_this_step = true
if step_result.exception
if #exceptions.include?(step_result.exception)
#hide_this_step = true
return
end
#exceptions << step_result.exception
end
if step_result.status != :failed && #in_background ^ step_result.background
#hide_this_step = true
return
end
#status = step_result.status
return if #hide_this_step
set_scenario_color(step_result.status)
#builder << "<li id='#{#step_id}' class='step #{step_result.status}'>"
end
def build_step(keyword, step_match, status)
# Do nothing
end
end
end
end
When you run Cucumber, tell it to use the custom formatter:
cucumber -f Cucumber::Formatter::HtmlStepless -o output.htm

Specify a page for pagination - Laravel 4

I'm trying to "remember" the page the user was on as he browses through records so that when he returns to the list, he is returned to the page where he left off.
How do I change the "current page" value for paginator?
I've tried Input::set('page', $x); but there's no such function.
$_GET['page'] = $x; doesn't work too.
This the code:
$list = Publication::orderBy($this->data['sort_by'], $this->data['order_by']);
foreach ($this->data['filter_data'] AS $field => $value) {
$list->where($field, 'LIKE', "%$value%");
}
$this->data['list'] = $list->paginate(15);
I looked at the API --- turns out this is much easier now in 2014.
All you have to do is set
Paginator::setCurrentPage(2);
any time before you call ->paginate(), I believe, and it should override the page set (or not set) by ?page=.
You can adjust the page of the pagination environment through the DB connection.
DB::getPaginator()->setCurrentPage(2);
Not entirely sure but you might be able to go through your model with something like this.
Publication::getConnection()->setCurrentPage(2);
If the above isn't working (as it seems from your comment), then do it with an instance of Publication.
$publication = new Publication;
$publication->getConnection()->setCurrentPage(2);
$list = $publication->orderBy(...);
Try
$pager->setCurrentPage(2);

ActiveAdmin - Filter with default value

Would like to know is that possible to have filter with default value with active admin? This will be helpful for preloading the data for the admin user.
filter :country, :default=>'US'
You can do it by defining before_filter
before_filter :only => [:index] do
if params['commit'].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
UPD:
in some cases you need to set filter if params[:q] is empty or params[:scope] empty
so this might work better
before_filter :only => [:index] do
if params['commit'].blank? && params['q'].blank? && params[:scope].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
Adapted Fivells answer to work correctly with scopes and downloads. Feels hacky but seems to do the job. Annotated intention in comments.
before_filter only: :index do
# when arriving through top navigation
if params.keys == ["controller", "action"]
extra_params = {"q" => {"country_eq" => "US"}}
# make sure data is filtered and filters show correctly
params.merge! extra_params
# make sure downloads and scopes use the default filter
request.query_parameters.merge! extra_params
end
end
Fixing issue with "Clear Filters" button breaking, updated answer building on previous answers:
Rails now uses before_action instead of before_filter. It belongs in the controller like so:
ActiveAdmin.register User do
controller do
before_action :set_filter, only: [:index]
def set_filter
# when arriving through top navigation
if params.keys == ["controller", "action"]
extra_params = {"q" => {"country_eq" => "US"}}
# make sure data is filtered and filters show correctly
params.merge! extra_params
# make sure downloads and scopes use the default filter
request.query_parameters.merge! extra_params
end
end
params.delete("clear_filters") #removes "clear_filters" if it exists to clear it out when not needed
end
end
Note, ActiveAdmin uses ransack for queries (ex. {"q" => {"country_eq" => "US"}}), check out https://activerecord-hackery.github.io/ransack/getting-started/search-matches for more matches if you need something more complex than "_eq".
Also, previous answers leave the "Clear Filters" button broken. It doesn't clear the filters, the filters set here are simply re-applied.
To fix the "Clear Filters" button, I used this post as a guide How to keep parameters after clicking clear filters in ActiveAdmin.
#app/assets/javascripts/active_admin.js
# Making clear filter button work even on pages with default filters
$ ->
$('.clear_filters_btn').click ->
if !location.search.includes("clear_filters=true")
location.search = "clear_filters=true"
This removes all search params (ie filters) and adds "clear_filters=true" so the controller can tell the request came from the "Clear Filters" button.
before_action only: [:index] do
if params['commit'].blank?
extra_params = {"country_eq" => "US"}
params['q'] = {} if params['q'].blank?
params['q'].merge! extra_params
request.query_parameters.merge! extra_params
end
end

Resources