Git Product home page Git Product logo

datagrid's Introduction

Bogdan

TODO: Write a gem description

hello

Installation

Add this line to your application's Gemfile:

gem 'bogdan'

And then execute:

$ bundle

Or install it yourself as:

$ gem install bogdan

Usage

TODO: Write usage instructions here

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

datagrid's People

Contributors

aepyornis avatar artofhuman avatar barendt avatar benolee avatar bogdan avatar dgodd avatar dmitry-ilyashevich avatar extravert-ir avatar fossabot avatar francois avatar gabebw avatar hamin avatar jasonpaluck avatar jjbohn avatar jswanner avatar ka8725 avatar leomao10 avatar loqman avatar lucasefe avatar markedmondson avatar mipearson avatar nicolai86 avatar olejrosendahl avatar robotdana avatar sanks02 avatar shanlalit avatar swlkr avatar yrgoldteeth avatar zhuravel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datagrid's Issues

Is Ruport the way to export csv?

You state that Datagrid can export csv, but I can only find the description on how to save as pdf using Ruport. Do you also use Ruport to create a csv?

Thanks.

No way to specify CSV-only columns

Consider the following: we want to supply HTML specific decoration for a particular column when it is rendered as HTML:

column :mything, :html => true do |asset|
  pretty_colours asset.mything
end

I assumed that I'd then be also able to specify something like:

column :mything, :csv => true

But this is not the case.

Right now there isn't a way to replicate a HTML-only column for CSV exports.

Looking at the code, I can't see a way to implement it without breaking the existing Column#html? and Column#data? methods.

If you can give me an idea of how you'd like this to work I am happy to implement it.

Another option would be for something like this:

column :mything, :html => true do |asset|
  if html?
    pretty_colours asset.mything
  else
    asset.mything
  end
end

Refactor to add Datagrid::Row concept

I think we are missing a Row concept to handle things like #78 (and one solution debated in #79). Working with table data is row-oriented, but there is no such object between Grid → ___ → Column. The problem is that Datagrid expects too much to be working with naked ActiveRecord objects, instead of holding its own concept of a Row object. The changes could look something like this:

row = Datagrid::Row.new(grid, asset)
row.asset #=> #<ActiveRecord ...>
row.decorated_asset #=> #<MyDecoratedObject name: "...", price: "...">
row.to_hash #=> {name: "...", price: "..."}
row.columns #=> ["...", "..."]
# ...

This could be used to clean up the code throughout. Wherever we accept naked ActiveRecord assets we could do this to avoid breaking the API:

to_hash(asset)
  asset = Datagrid::Row.new(self, asset) unless asset.is_a? Datagrid::Row
  asset.to_hash
end

Give me a 👍 on the idea in principle, I can look at it further.

Cannot seem to get the wiki post on dynamic scopes to work

Everything works correctly if I use the following for static scope.

class ProjectsController < ApplicationController
def plautReport
@project=Project.find(params[:id])
@plaut_report = PlautReport.new(params[:project])
@assets = @plaut_report.assets.page(params[:page])
end
end

class PlautReport
include Datagrid
scope { Stock.joins(:options).select("fullname,symbol,current_price,earnings_date,dividend_date, sim_mov_avg_thirty, boll_two, Boll_three, beta, key,expiration_date,strike_price, bid, cushion, bid_premium").order("fullname")
end

However, I plan for this table to get quite large and want to restrict it to a project (which has many stocks in my model)

When I change my controller to the following:
def plautReport
@project=Project.find(params[:id])
@plaut_report = PlautReport.new(params[:project])
@plaut_report.scope do
@project.stocks
end
@assets = @plaut_report.assets.page(params[:page])
end

I get the following error message:
wrong number of arguments (1 for 0)
app/controllers/projects_controller.rb:13:in `plautReport'
(line 13 is the following line: @assets = @plaut_report.assets.page(params[:page])

Model definitions:
class Project < ActiveRecord::Base
has_many :stocks, :dependent => :destroy
has_many :options, :through => :stocks

class Stock < ActiveRecord::Base
belongs_to :project, :foreign_key =>'project_id'
has_many :options, :class_name =>'Option'

class Option < ActiveRecord::Base
belongs_to :stock, :foreign_key =>'stock_id'

class.scope prevents controller from assigning scope

In our usage we need to scope a lot of things by the current_user, which means passing an argument into the Datagrid model from the controller.

First attempt:

class ThingReport
  include Datagrid

  attr_accessor :current_user

  scope do
    @current_user.things
  end
end

# Controller:
@things = ThingReport.new(params[:things])
@things.current_user = current_user

Unfortunately the scope is evaluated in the context of the class, not the instance.

Our current solution:

class ThingReport
  include Datagrid

  attr_accessor :current_user

  scope do
    # Just a dummy scope to satisfy the class & load the driver.
    # We just override our own scope instance method.
    Thing  
  end

  def scope
    @current_user.things
  end

  # assets needs to be redefined here because `Association#scoped` and `CollectionProxy#scoped`
  # take 0 arguments. Only ClassMethods#scoped takes options, which driver#to_scope breaks.
  def assets
    scope.scoped
  end
end

I'm wondering if there are any better solutions for this or any thoughts on adding an allowance to Datagrid for handling more dynamic scopes.

'ilike' is not recognizing in mysql and working fine in pg.

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ilike '%country3%')' at line 1: SELECT COUNT(*) FROM countries WHERE (name ilike '%country3%')

In my model I have given like this,
filter(:name,:string) {|value| where("name ilike '%#{value}%'")}

Adding a feature

I have been using Datagrid and It works great. But now I want a feature that the users can choose columns to be shown on the page. Can you recommend me how to do that?

let enum select options use instance method

I just create a report class like this:

  class ContactReport 
    include Datagrid

    datagrid_attribute :current_user
    datagrid_attribute :sites

    def initialize(current_user, attributes = {})
      super(attributes)
      self.current_user = current_user
      if current_user
        self.sites      = current_user.sites.active.doing_jsa
        scope do
          PsmContact.index_scope.restricted(sites).includes(:user)
        end
      end
    end
  end

and now I want to add a enum filter, and its select item should be current_user.sites

    filter(:site_id, :enum, :select => lambda { current_user.sites.flatten }, :prompt => "All sites") do |value|
      where(:site_id => value)
    end

However, I could not do that because the context for the lambda is ContactReport and it do not have a current_user methods.

Could be helpful if you can enable the select option to use current instance's method

sort picklist

I have the following filter:
filter(:first_name, :enum, :header => "First Name", :select => proc { User.all.map(&:first_name) }) do |value|
self.joins(:user).where(:users => { :first_name => value})
end

How would I get the first_name sorted ASC?

Thanks,
Dave

Request: ability to stream a CSV representation of DataGrid

Hey @bogdan, Nate here from Hired.

We're using the to_csv feature of DataGrid to export large data sets within the admin tool. As the size of our data continues to grow, to_csv is consuming a lot more memory. With really large data sets, it uses up too much memory and can crash our Sidekiq workers (CSV exports are processed in the background).

I thought a nice way to get around this problem would be to stream a CSV export directly to the filesystem or S3 instead of building up the entire CSV in memory and then writing the file.

How hard do you think it would be to add something like a stream_csv method or something like that to DataGrid?

cc: Hired team @allangrant, @wnadeau, @petermin, @cgag, @schlende

Rails 3.2 + Kaminari + Pg - select count bug

Kaminari tries to count db table records but fails because it includes always an order clause.

If you do something like: Model.order('id DESC').page(params[:page]) in controller works fine, but using datagrid the count is like this:

SELECT COUNT(*) FROM model_table ORDER BY id DESC

I've created a monkey patch for apply_order method inside ordering.rb, this is the code:

def apply_order(assets, column)
order = column.order
if self.descending?
if column.order_desc
assets.reorder("#{column.order} ASC")
else
assets.reorder("#{column.order} DESC")
end
else
assets.reorder("#{column.order} ASC")
end
end

appears to work nice :)

But since it is my first report I don't know if this code doesn't mess other stuffs.

Can't get filter to work in form

I have it all working for me now, including the filter, except for when I want to add filter inputs in the form. Thanks again for all your help

I get a stacktrace error found below (partial).....

["/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activemodel-3.2.9/lib/active_model/naming.rb:163:in model_name_from_record_or_class'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activemodel-3.2.9/lib/active_model/naming.rb:158:inparam_key'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/helpers/form_helper.rb:369:in form_for'", "/Users/erikf/ruby/stocks/app/views/reports/show.html.erb:5:in_app_views_reports_show_html_erb___4509035156450343395_70268758953200'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/template.rb:145:in block in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/notifications.rb:125:ininstrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/template.rb:143:in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/template_renderer.rb:47:inblock (2 levels) in render_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/abstract_renderer.rb:38:in block in instrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/notifications.rb:123:inblock in instrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/notifications/instrumenter.rb:20:in instrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/notifications.rb:123:ininstrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/abstract_renderer.rb:38:in instrument'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/template_renderer.rb:46:inblock in render_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/template_renderer.rb:54:in render_with_layout'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/template_renderer.rb:45:inrender_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/template_renderer.rb:18:in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/renderer.rb:36:inrender_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_view/renderer/renderer.rb:17:in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/abstract_controller/rendering.rb:110:in_render_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/streaming.rb:225:in _render_template'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/abstract_controller/rendering.rb:103:inrender_to_body'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/renderers.rb:28:in render_to_body'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/compatibility.rb:50:inrender_to_body'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/abstract_controller/rendering.rb:88:in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/rendering.rb:16:inrender'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/instrumentation.rb:40:in block (2 levels) in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/core_ext/benchmark.rb:5:inblock in ms'", "/Users/erikf/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/benchmark.rb:295:in realtime'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/core_ext/benchmark.rb:5:inms'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/instrumentation.rb:40:in block in render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/instrumentation.rb:83:incleanup_view_runtime'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-3.2.9/lib/active_record/railties/controller_runtime.rb:24:in cleanup_view_runtime'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/instrumentation.rb:39:inrender'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/implicit_render.rb:10:in default_render'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/implicit_render.rb:5:insend_action'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/abstract_controller/base.rb:167:in process_action'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/action_controller/metal/rendering.rb:10:inprocess_action'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/actionpack-3.2.9/lib/abstract_controller/callbacks.rb:18:in block in process_action'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:414:in_run__1637435136998353384__process_action__4198382751368752171__callbacks'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:405:in `__run_callback'", "/Users/erikf/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.9/lib/act

===================URL called========================
http://localhost:3000/reports/4

==================show.html.erb=============================

<div class="left">

<% begin %>
<%= form_for [@report, @options], :html => {:method=>:get} do |f| %>
    <% @report.filters.each do |filter| %>
      <div class="filter">
        <%= f.datagrid_label filter %>
        <%= f.datagrid_filter filter %>
      </div>
      <div class="clear"></div>

    <div class="filter">
      <%= f.submit %>
    </div>
      <% end %>
    <div class="clear"></div>
  <% end %>
  <br/>
  <%rescue =>exception %>
  <%= exception.backtrace %>
  <% end %>

  <%= datagrid_table(@report, @assets) %>
  <%= paginate @assets %>

=================report.rb========================
Class Report
include Datagrid
scope {
Option.includes(:stock)
}

filter(:project_id, :integer)
column(:fullname) do |stock|
Option.first.stock.fullname
end

=================ReportsController======================
class ReportsController < ApplicationController

def show
id=params[:id]
@report = Report.new(:project_id =>id)
@assets = @report.assets.page(params[:page]).per(25)
end

end

==============routes=============
resources :reports, :only=>[:show]

Multi-tenancy with Postgresql schemas, select filter issue

I have rails 3.2 app that is multi-tenant enabled using the Apartment gem and Postgresql schemas. Under normal circumstances Apartment::Elevators switches the Postgesql schema on a per-request basis.

So, suppose I'm using Datagrid and I define a filter like this:
filter( :user_id,
:enum,
:select => User.order(:last_name).all.map{ |u| [u.full_name, u.id] },
:header => "User",
) { |value, scope| scope.where{user_id.in values} }

The query should grab the list of users from the subdomain specific schema, but instead is pulling from the public schema (where this user list is always blank).

I'm trying to figure out how the query is built by Datagrid to explain this behavior but I'm pretty vexed. Where does this happen? Do you have any suggestions?

Filter OR or AND

hi,
a new issue !
the multiple filter don't seems work with a "AND" junction, only with "OR".

I explain with your example on http://datagrid.herokuapp.com/ in the basic if you choose :

disabled : NO
registration type : LINKED IN

the result is 3
3 [email protected] Linked in 2 2011-08-30 19:16:59 UTC Yes
5 [email protected] Linked in 3 2011-08-30 19:17:00 UTC No
10 [email protected] Linked in 9 2011-09-02 05:17:02 UTC No

the results are corrects if i search disabled OR registration type, but I think it's not best default way for a filter.

How to change OR relation to AND relation ?
Maybe a option can be implemented ?

Thanks a lot

Rails 4

Have you tested with Rails 4? Are there any known or expected issues?

Support for data aggregation?

I'm looking for a way to dynamically aggregate calculated column data based on values in other columns (basically, group-by functionality with a way to hide unused columns). In the current implementation, I don't see one. Do you think it's possible? If it's not supported, do you want me to try doing this and send you a patch (in this case, I'd appreciate any clues to help me get started)?

:enum and :header

Hi,

really great gem, I play with him since one hour only but I seems that ":header" don't be use with filter :enum.

I try before :enum, after :enum, after :select. No effect, just error 500.

It's me or....

Uninitialized constant FooReport::Datagrid".

I am trying your datagrid gem and am having an elementary problem. Before I go hack something I shouldn't I thought I would ask. My error is that when I refresh the page I get: "uninitialized constant ProgramReport::Datagrid". Weird, right? Here's the source code I am using... Thanks for any help!

-- Pito

models/program_report.rb:

class ProgramReport
include Datagrid

scope do
Program
end

column(:id)
column(:name)
end

controllers/programs_controller.rb:
def index
@program_report = ProgramReport.new(params[:program_report])
@assets = @user+report.assets.page(params[:page])
end

Allow for mapping row assets using a block

We use the following monkey patch in our app:

module Datagrid::Core::ClassMethods
  def row(&block)
    @row_value = block
  end

  def row_asset(asset)
    @row_value.call(asset)
  end
end

class Datagrid::Renderer
  def rows(grid, assets, options = {})
    result = assets.map do |asset|
      asset = grid.class.row_asset(asset) # :monkey:
      @template.render :partial => "datagrid/row", :locals => {:grid => grid, :options => options, :asset => asset }
    end.join

    _safe(result)
  end
end

This lets us define a block for wrapping each asset:

class ProjectReport
  include Datagrid
  scope  { Project }
  row    { |asset| ProjectDecorator.new(asset) }
  column :name
  # ...
end

Rather than duplicating presentation logic in each "column" block, I think this allows for a tidy solution without changing the existing flexibility.

  • Not sure if row is the best DSL method name. (I thought it gives nice symmetry to column.)
  • Is Renderer#rows the best place to hook it in? (Mapping all the assets to an array in the table method might break pagination if you're still expecting a scope in the _table partial.)
  • The row_value block might also be settable for the instance, similar to how scope works now.

I can clean it up and send a PR if this feature sounds useful.

Enable customization of <td>

Currently, I found no way to set my own class on a <td>. Maybe there's a workaround? I believe an ability to specify custom classes on a <td> should be extremely useful in some cases.

Per investigation I found no way to specify arbitrary class on a column. See the chain:

  1. _row.html.erb
  2. #datagrid_column_classes

Going even further, I believe datagrid should allow full customization of <td>'s html attributes. Among the most popular attributes there are id, title, data- and others.

DateTime filter

Is there any reason why there is not a datetime filter?
I see that in Datagrid::Utils there's a parse_date method that always uses Date instead of DateTime. I think that changing that method to use DateTime instead of date would allow for date and datetime filters without breaking anything....
What do yo think? Do I implement another filter to allow this or can I change that method?
I'll make a pull request with any of those solutions.

Grid for nested controllers

Hi, your gem is really cool, but there is no one more feature which should be here in my opinion.
Imagine you have controller which serves nested route /users/:user_id/tasks:

class TasksController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    @tasks = @user.tasks
  end
end

Currently I see how to do it but it seems as a hack:

class TasksController < ApplicationController
  def index
    @grid = TasksGrid.new((params[:tasks_grid] || {}).merge(:user_id => params[:user_id]))
    @assets = @grid.assets.paginate(:page => params[:page])
  end
end

I use your gem with inherited_resources and I'he created mixin which provides helpers for getting @assets and @grid.

But there is the same problem in this approach. I don't now may datagrid provides this ability but I've not find solution.

The best solution here I think will be in changing creation of grid object. For example:

@grid = TasksGrid.new(params[:tasks_grid], parent)

As you can see I suggest to pass scope as a second parameter.

How to handle a field that may be nul

I have a column in a report that sometimes will be nil.

I tried these two approaches:

column(:assetnum, :header => "Asset") do |record|
Thing.find(record.thing_id).assetnum
end

Returns:
ActiveRecord::RecordNotFound in AdminReportsController#index

and

column(:assetnum, :header => "Asset") do |record|
Thing.find_by_id(record.thing_id).assetnum
end

Returns:
undefined method `assetnum' for nil:NilClass

Bad UX with :multiple=>true in filter

The multiple value filter UX has some issues.

After the form is submitted the values are repopulated in the newly loaded form but with the quotes escaped. I'm not sure why this occurs. I am using the datagrid gem in Rails 3. But this should not be the default behavior.

For example:

I enter ["New York", "25"]

in the input field in the filter form. The data is filtered and the newly loaded form contains

["[\"New York, NY\", \"25\"]"] in the input field.

Although the array input is not ideal, I think the first correction would be to stop escaping various characters and also not wrapping the query in a second set of square brackets.


Also, I believe that it would be much more natural and obvious for the user to be presented with multiple input fields, each with labels. This would require a little more engineering than the first part but I think it is quite necessary to the evolution of this product.

I am suggesting some functionality where I can setup multiple input fields where each of the values are then passed to a single code block.

Editable rows/columns

Would it be possible to extend this to enable editing the data in the table?

I could see the following scenarios: 1)delete the whole line 2)change a single value

Simultaneously AND\OR filtering. Filter builder

HI! Small question. I want filter some entries from table Users. My query like this: name like "Jhon" OR name like "Bob". So, I need some similar filters in form and select box like OR between that (filter builder). How to realize that with your gem?

Прошу помощи :) Мне из таблицы Users надо выбрать несколько записей. Выборка удовлетворяет условию name like "JHon" OR name like "Bob", т.е. на одно поле мне надо применить два фильтра, которые между собой относятся как OR. Как такое реализовать при помощи вашего гема? И возможно ли сделать бесконечную вложенность этих фильтров (... OR ... OR ... OR ...), просто добавляя через JS поля в форму?

Filter with hidden field

Hi bogdan,

is there a way to configure a filter that outputs a field and a hidden field, and uses the hidden field as the value for the filter?

What I'm trying to do is to have a filter with autocomplete (it's a relation to another table, and has too many records to load them at once). So it would need to print a regular field in the form, and a hidden field as well, then it should only use the hidden field to perform the filtering. This way anyone can hook up any autocomplete library (eg: jquery-ui.autocomplete).

I was looking at the code, and thought the best way to do it is to add a new option to the filters (named something like use_hidden).

What do you think about it? Is that the best way to implement it? Let me know, and I'll make a pull request.

Thanks, and great gem!

Use controller's variable in the datagrid's columns

I need to use controller's variable (current_user) to conditionally set column value (f.ex., show whether the current_user "owns" the item).
Assigning the value in constructor did not help.

I'm reluctant to do a dirty hack and introduce a class variable for the task. Is there a better way to pass a variable to column?

Many thanks for your time and effort devoted to the project.

converting class name to GET param in order link

In my project I have report class located in subdirectory of models directory like 'app/models/reports/users.rb' and a class name for that file is 'Reports::Users'.
Filter form is OK, it makes GET param as 'reports_users[]' but ordering makes it only as 'users'.
As I understand this is because of 'lib/datagrid/active_model.rb' on line 22 'self.to_s.underscore.split('/').last'. It converts it to 'reports/users' and than takes the last only.

dynamic parameters for the scope value

On the examples, when I define the scope block y doesn't show how to accept parameters, like the initial relation.

This could be useful, and very needed (by me, at least).

Example:

class Report
  include Datagrid
  scope do
    current_user.things
  end
end

current_user should somehow passed as an argument when being instantiated.

May there's a way, but I'm not that sure.

grid and link

hi,
it's me again, I love this gems, really...

How to make a link with the item of datagrid ? I try to make a link to the "show" page from a cell's content.

i try something like : column(:id, :url => lambda {|ghy| ghy.id})

but error : undefined method `model_name' for Fixnum:Class

Any idea ?
Thk

PDF Export Support

I see on the readme file that there is a way to export to CSV. I wonder if there's a way to add new export format. If not, is it easy to do it?

Let me know if you think there's and easy way to do it.

Thanks

Additional option for :multiple => true

I think, at filter where :multiple set to true, nedded additional option for building request about relation between filter items (OR or AND). At this moment, filter use OR. Something like this:

filter(:group, :enum,
    :select => lambda {Group.all.map {|p| [p.name, p.id]}},
    :header => "Group",
    :multiple => true,
    :relation => :and ,                 # this option
    :include_blank => true
  ) do |value|
.........
end

Fancier way to generate HTML for columns (like WiceGrid)

Hey Bogdan

Indeed a very useful gem you are providing here. Thank you for your effort, we are examining it for a project in our company.

We like WiceGrid here a lot, but since we are using MongoDB for this project, it doesn't suit our needs.

All in all, Datagrid seems very powerful, and still simple. It only feels a bit cryptic to me in many places. For example, I love WiceGrid's easy to style column method:

<%= grid(@tasks_grid) do |g|

  g.column :name => 'ID', :attribute => 'id' do |task|
    <strong>task.id</strong> <!-- YOU CAN PUT ANY HTML CODE YOU LIKE IN HERE! -->
  end
end %>

Would it be hard to do something in Datagrid and not having to rely on partials? So you wouldn't even really have to define an XxxReport class, but define it on the fly within a view?

class SimpleReport

  include Datagrid

  scope do
    User.includes(:group)
  end

  # Instead of having this...
  filter(:category, :enum, :select => ["first", "second"])
  filter(:disabled, :eboolean)
  filter(:confirmed, :boolean)
  filter(:group_id, :integer, :multiple => true)
  integer_range_filter(:logins_count, :integer)
  filter(:group_name, :string, :header => "Group") do |value|
    self.joins(:group).where(:groups => {:name => value})
  end

  # ...and this...
  column(:name)
  column(:group, :order => "groups.name") do |user|
    user.name
  end
  column(:active, :header => "Activated") do |user|
    !user.disabled
  end
end
# ...simply have this in the view:

<%= filter(:category, :enum, :select => ["first", "second"]) do |f| %>
  Please choose a category <%= f %>
<% end %>

<%= filter(:disabled, :eboolean) do |f| %>
  <%= f %> Should only displayed ones be in the list?
<% end %>

...etc...

<%= column(:name) %>
<%= column(:group, :order => "groups.name") do |user| %>
    This is the name: <%= user.name %>
<% end %>

...etc.

You get the picture? The code above would on the fly define the report class' settings and output the generated code on the fly.

Just some brainstorming here, maybe it's impossible what I'm asking for. But my feeling tells me that this would really feel like the "Rails way". :-)

Best wishes,
Josh

Min\max value for filter

For date\integer\float filter something like this

filter(:from_created_at, :date, :default => Date.today, :max => Date.today >> 12) do |value|
  where(["created_at >= ?", value])
end
filter(:from_created_at, :date, :default => Date.today, :min => Date.today - 7) do |value|
  where(["created_at >= ?", value])
end
filter(:from_created_at, :integer, :default => Date.today, :max => 512) do |value|
...
end
filter(:from_created_at, :integer, :default => Date.today, :min => -512, :max => 1024) do |value|
...
end

It's add an option for input tag

New 'i18n' option for columns

I was thinking of adding a new option for a column that uses I18n gem to localize the column results.
The idea is that the option i18n is passed to a column, the value of the column is passed to the I18n.l or I18n.t methods, with the options passed.
Something like this:

column(:created_at, :i18n => {:format => :short}) # this would call I18n.l(value, {:format => :short})
column(:name, :i18n => {:scope => "scope.of.the.translation"}) # this would call I18n.t(value, {:scope => "scope.of.the.translation"})

The method that's called is the localization method for dates and the translation method for any other type (checking that the object responds to strftime, like the I18n.l method does).

This would be a shorthand for:

  column(:created_at) do |obj|
    I18n.l(obj.created_at, :format => :short) if obj.created_at
  end
  column(:name) do |obj|
    I18n.l(obj.name, :scope => "scope.of.the.translation") if obj.name
  end

What do you think? Do I make a pull request with this functionality?

:enum not displaying in production

Hi I defined a filter like my :categoria filter is not working properly in production, it just displays blank:

scope do
MonthlyReport.scoped_by_categoria(User.current_user.categories.map(&:name))
end

filter(:categoria, :enum, :select => categorias, :default => lambda{User.current_user.categories.map(&:name).sort.first})
)

filter(:categoria, :enum, :select => categorias, :default => lambda{User.current_user.categories.map(&:name).sort.first})

In my views I'm just using
<%=f.datagrid_label @reports.filters[0], :class => "control-label"%>
<%=f.datagrid_filter @reports.filters[0], :class => "input-xlarge" %>

Mongoid 3 support

Any plans to support mongoid 3?

Seems like column ordering doesn't work in mongoid 3.

integer and date range

Hi,

Simple question : how to internationalize the «from» & «to» in integer or date range ? It's possible have a :header option ?

thk a lot.

Dynamic values for an enum filter

I need to be able to define an enum filter with variable values.

Imagine the following code:

class Something

  include Datagrid

  scope do 
    User
  end

  filter :package_id, :enum, select: lambda { raise "Ouch"  }

end

If you go to the console and just load the class (no instantiation) you'll get an error saying "Ouch"

I think the lambda code should be evaluated only at the moment of instantiation... Don't you think? That way we should be able to change the enum list for different values. I mean, it's a drop-down menu... it may change.

What do you think? Can we change that?

Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.