Giter Site home page Giter Site logo

mobility-ransack's Introduction

Mobility Ransack

Gem Version Build Status Code Climate

Search on translated attributes with Mobility and Ransack.

Installation

Just add the gem to your Gemfile:

gem 'mobility-ransack', '~> 1.2.2'

Now enable the ransack plugin in Mobility's configuration:

Mobility.configure do
  plugins do
    ransack

    # ...
  end
end

This will enable the ransack plugin for all models. Disable it by passing false to the ransack option:

class Post < ApplicationRecord
  extend Mobility
  translates :foo, ransack: false
end

You can search on foo with Ransack just like any untranslated attribute, e.g. if Post has a title attribute translated with the Jsonb backend:

Post.ransack(title_cont: "foo").result
#=> SELECT "posts".* FROM "posts" WHERE ("posts"."title" ->> 'en') ILIKE '%foo%'

Other backends work exactly the same way.

License

The gem is available as open source under the terms of the MIT License.

mobility-ransack's People

Contributors

f1sherman avatar jalkoby avatar kevynlebouille avatar mhenrixon avatar petewalker avatar shioyama avatar tagliala 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

Watchers

 avatar  avatar  avatar

mobility-ransack's Issues

Mobility-ransack version 1.2.0 creates wrong queries and result method not working

Hi, I am trying to add mobility-ransack to the project and I faced some issues with the 1.2.0 version - after downgrading to 1.0.1 everything seems to work for me.
I am using:

  • Rails 7
  • Ruby 3
  • Mobility backend: table

The first error that I get is

ActionView::Template::Error (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "model_translations_en"

My query wants to use an alias with 'en' added after 'translations' but no alias is provided at the inner join. Also after some debugging, I came to the conclusion that the result method in 'Search' module is not used during ransack.result actions.

My solution:
I added the line require "mobility/ransack" in plugins/ransack.rb file and now the plugin is working correctly.

Searching for objects in belongs_to associations

Isn't that possible or am I missing something? For instance:

class Athlete < ApplicationRecord
	belongs_to :playing_position
end

class PlayingPosition < ApplicationRecord
	extend Mobility
	
	translates :name
end

pry(main)> Athlete.ransack(playing_position_name_cont: 'pont').result.size
(0.7ms) SELECT COUNT(*) FROM athletes LEFT OUTER JOIN playing_positions ON playing_positions.id = athletes.playing_position_id WHERE PlayingPosition_name_pt_br_string_translations.value LIKE '%pont%'
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'PlayingPosition_name_pt_br_string_translations.value' in 'where clause'
from /Users/fabiano/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in _query' Caused by Mysql2::Error: Unknown column 'PlayingPosition_name_pt_br_string_translations.value' in 'where clause' from /Users/fabiano/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in _query'

predicate search breaks after upgrading to v1.2.2

Hi, I updated mobility-ransack to 1.2.2 which also updates ransack to 4.1.1. After adding the ransackable_attributes and associations, I expect it to work like before but now predicate search stops working.

I am not sure if this is an upstream issue or something related to this plugin.

# Story class
class Story < ApplicationRecord
  extend Mobility
  has_many :story_updates, -> { kept.order(created_at: :asc) }, dependent: :destroy, inverse_of: :story
  translates :title, :description, :outcomes, :source

  def self.ransackable_attributes(auth_object = nil)
    %w[title, description, outcomes, source, country]
  end

  def self.ransackable_associations(auth_object = nil)
    %w[story_updates]
  end
end

# StoryUpdate class
class StoryUpdate < ApplicationRecord
  extend Mobility
  belongs_to :story

  translates :title, :description

  def self.ransackable_attributes(auth_object = nil)
    %w[title description]
  end
end

Detailed Logs:

ActionView::Template::Error:
       undefined method `title_or_description_or_outcomes_or_source_or_story_updates_title_i_cont_any' for Ransack::Search<class: Story, base: Grouping <combinator: and>>:Ransack::Search
     # ./app/views/stories/_search.html.erb:5:in `block in _app_views_stories__search_html_erb__1766051873175227570_75060'
     # ./app/views/stories/_search.html.erb:1:in `_app_views_stories__search_html_erb__1766051873175227570_75060'
     # ./app/views/stories/index.html.erb:5:in `_app_views_stories_index_html_erb___3856470445803634[16](https://github.com/compassionprojects/socialchange/actions/runs/7389850038/job/20103545544#step:8:17)1_75040'
     # ./spec/requests/stories_spec.rb:7:in `block (3 levels) in <main>'
     # ------------------
     # --- Caused by: ---
     # NoMethodError:
     #   undefined method `title_or_description_or_outcomes_or_source_or_story_updates_title_i_cont_any' for Ransack::Search<class: Story, base: Grouping <combinator: and>>:Ransack::Search
     #   ./app/views/stories/_search.html.erb:5:in `block in _app_views_stories__search_html_erb__[17](https://github.com/compassionprojects/socialchange/actions/runs/7389850038/job/20103545544#step:8:18)6605[18](https://github.com/compassionprojects/socialchange/actions/runs/7389850038/job/20103545544#step:8:19)73175[22](https://github.com/compassionprojects/socialchange/actions/runs/7389850038/job/20103545544#step:8:23)7570_75060'

Another thing to note is that in rails console, using predicate title_cont results in an empty query

Story.ransack(title_cont: "Totam").result.to_sql
=> "SELECT \"stories\".* FROM \"stories\""

where as using association predicate story_updates_title_cont results in a proper sql

 Story.ransack(story_updates_title_cont: "Totam").result.to_sql
=> "SELECT \"stories\".* FROM \"stories\" LEFT OUTER JOIN \"story_updates\" ON \"story_updates\".\"discarded_at\" IS NULL AND \"story_updates\".\"story_id\" = \"stories\".\"id\" WHERE (\"story_updates\".\"title\" ->> 'en') ILIKE '%Totam%'"

which is a bit strange

Source

Automatic ransack configuration for table backend

I'm using rails with activeadmin, I want to be able to filter using all translations:

filter :translations_title_i_cont, as: :string, label: 'Title Search'

To make it work I've had to make a bit of magic in application_record.rb:

class ApplicationRecord < ActiveRecord::Base
  extend Mobility

  self.abstract_class = true

  class << self
    alias mobility_translates translates

    def translates(*attributes, **options)
      mobility_translates(*attributes, **options)
      translation_class = const_get(:Translation)
      translation_class.define_singleton_method(:ransackable_attributes) do |_arg = nil|
        attributes.map(&:to_s)
      end
      translation_class.define_singleton_method(:ransackable_associations) do |_arg = nil|
        []
      end
    end
  end
end

Would it be possible for this gem to define those two methods automatically?

Issue with form helpers

Hello!

I'm using Ransack form helpers to perform searches on models:
<%= search_form.search_field :title_cont, class: 'form-control', placeholder: 'Name' %>

Unfortunately, that returns an error
undefined method title_cont' for Ransack::Search<class: Training, base: Grouping <combinator: and>>:Ransack::Search

Here is my controller:

def index
    @search = @trainings.i18n.ransack(params[:q])
    @trainings = @search.result(distinct: true)
  end

I'm on Rails 7.0.4.3, Ruby 3.2.2 with mobility, mobility-ransack and ransack 4 installed.

Rails 7 deprecated use of sum

On Rails 7 I'm getting deprecation errors:

DEPRECATION WARNING: Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4. Sum of non-numeric elements requires an initial argument. (called from visit_collection at /home/travis/build/FutureProofRetail/business-server/vendor/bundle/ruby/3.1.0/gems/mobility-ransack-1.1.0/lib/mobility/ransack.rb:15)

Issue seems to be here; to fix, you'll need to pass add an argument into sum; I'd put in a PR but I'm not sure what that arg should be.

Problem with sorting: private method `visit_Ransack_Nodes_Sort' called for #<Ransack::Visitor>

There is an error thrown

private method `visit_Ransack_Nodes_Sort' called for #<Ransack::Visitor>

when sorting is added to ransack params.

For example these:

Post.ransack(title_cont: "foo", s: "title").result
Post.ransack(title_cont: "foo", s: "created_at").result

are throwing the error, while calling without sorting parameter

Post.ransack(title_cont: "foo").result

is working correctly.

visit_Ransack_Nodes_Sort is indeed private method in Ransack::Visitor.

irb(main):018:0> Ransack::Visitor.private_instance_methods.include?(:visit_Ransack_Nodes_Sort)
=> true

It's called here

Ransack version dependency

I'm running into some trouble getting Ransack to work with Rails 5.2.2 (see activerecord-hackery/ransack#987). Upgrading Ransack to 2.1.1 seems to fix this, but this plugin explicitly pins the Ransack version to < 2.1.

Is there any reason why this couldn't be bumped to < 2.2?

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.