Git Product home page Git Product logo

dynamic_selectable's Introduction

DynamicSelectable

DynamicSelectable is a Rails gem that allows you to easily create collection_select fields with results that dynamically populate a related field. The dynamic population occurs with the help of the jQuery library jquery-dynamic-selectable written by Andrey Koleshko.

How about a use case? Let's say your application allowed users to look up parts for their vehicle. A user selecting their car's model might include the following:

  1. User selects the Make of their vehicle
  2. The Model field is populated with models of the selected Make
  3. User selects the Model of their vehicle

DynamicSelectable makes the above easy to do by providing a generator for your dynamic collection_select along with a new FormHelper method called dynamic_collection_select.

To see this gem in action, you can check out the sample application here.

Updating from 0.0.2

Warning: If you are updating from 0.0.2 you will need to re-generate any content created with rails generate dynamic_selectable:select.

Installation

Add the following line to your application's Gemfile:

gem 'dynamic_selectable', git: 'https://github.com/mattantonelli/dynamic_selectable.git'

Install the gem by running bundle install.

Run the gem's install generator:

$ rails generate dynamic_selectable:install

If you are using Devise for user authentication, you will want to skip authentication in the newly generated app/controllers/select/select_controller.rb:

class DynamicSelectable::SelectController < ApplicationController
  # skip_before_action :authenticate_user!
end

Finally, you'll want to add the following require to your application.js:

//= require jquery-dynamic-selectable

Now that you have DynamicSelectable installed, you're ready to start creating some dynamic_collection_select fields in your application!

Usage

The first step to creating a dynamic_collection_select is to generate a controller and route for it. Using the vehicle example from above, your Make and Model models might look like the following:

# == Schema Information
#
# Table name: makes
#
#  id         :integer          not null, primary key
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Make < ActiveRecord::Base
end
# == Schema Information
#
# Table name: models
#
#  id         :integer          not null, primary key
#  name       :string
#  make_id    :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Model < ActiveRecord::Base
  belongs_to :make
end

To generate the controller and route necessary for your selection of Make to dynamically populate your selection of Model, run the following:

# Usage: rails generate dynamic_selectable:select parent child value_method text_method [sort_col:asc/desc]
$ rails generate dynamic_selectable:select make model id name name:asc

Now you just need to build your form. The method dynamic_collection_select is very similar to collection_select, but contains the new dynamic_model parameter. This parameter is a symbol representing the child model whose collection will be populated based on the value selected in this parent field.

If you would like to submit the value of the dynamic_collection_select with the form, just add { submit_with_form: true } to the options hash.

def dynamic_collection_select(object, method, dynamic_model, collection, value_method, text_method,
                              options = {}, html_options = {})

A very simple form would look something like this:

<%= form_for(@vehicle) do |f| %>
  <div>
    <%= label_tag :make_id %>
    <%= dynamic_collection_select :vehicle, :make_id, :model, Make.all, :id, :name,
        { include_blank: true }, {} %>
  </div>

  <div>
    <%= f.label :model_id %>
    <%= f.collection_select :model_id, [], :id, :name, {}, {} %>
  </div>

  <%# ... %>
<% end %>

That's it. Happy selecting!

Overriding data attributes

By default, DynamicSelectable uses the object and method parameters of dynamic_collection_select to generate data attributes used by the gem's Javascript. Depending on your model, or if you are creating a form with a gem like Ransack, the values you provide for these parameters could prevent DynamicSelectable from generating the necessary data attributes properly. To resolve this, you can manually specify these attributes in a data hash within your tag's html_options hash. For example:

<%= dynamic_collection_select :q, :make_id_eq, :model, Make.all, :id, :name,
  {}, { data: { dynamic_selectable_url:    '/dynamic_selectable/makes/:make_id/models',
                dynamic_selectable_target: '#q_model_id_eq' } } %>

The value for dynamic_selectable_url can be found in your routes:

$ rake routes | grep dynamic
dynamic_selectable_make_models GET    /dynamic_selectable/makes/:make_id/models(.:format) dynamic_selectable/make_models#index

and the value for dynamic_selectable_target is generated with your form. This can be found by inspecting the child element in your web browser.

Removing generated content

Remove a generated controller/route

$ rm app/controllers/dynamic_selectable/models_controller.rb

and remove the related line from your routes.rb:

get ':make_id/models', to: 'models#index', as: :models

Complete uninstallation

$ rm -rf app/controllers/dynamic_selectable

and remove the following block from your routes.rb:

namespace :dynamic_selectable do
  # ...
end

Contributing

  1. Fork it ( https://github.com/mattantonelli/dynamic_selectable/fork )
  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 a new Pull Request

dynamic_selectable's People

Contributors

justinmcnamara74 avatar mattantonelli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

dynamic_selectable's Issues

Tilt autoload coffee_script warning

Need to investigate how to solve this warning, which appears during Capistrano deployment and RSpec tests, without having to add coffee-script to the Gemfile.

Phusion Passenger Error

After a new deployment using nginx and phusion passenger, the application fails to load with a 502 error. The following is displayed in the nginx error log:

[ 2015-04-13 13:40:38.0421 8139/7f81c14bc700 Pool2/Pool.h:777 ]: Process (pid=30506, group=/var/rails/ebb/current#default) no longer exists! Detaching it from the pool.
App 30519 stdout:
App 30478 stderr: /var/rails/ebb/shared/bundle/ruby/2.1.0/gems/actionview-4.1.6/lib/action_view/helpers/form_options_helper.rb:162:in `select': wrong number of arguments (1 for 2..5) (ArgumentError)
App 30478 stderr:   from /home/rails/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.44/lib/phusion_passenger/request_handler.rb:517:in `wait_until_termination_requested'
App 30478 stderr:   from /home/rails/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.44/lib/phusion_passenger/request_handler.rb:206:in `main_loop'
App 30478 stderr:   from /home/rails/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.44/helper-scripts/rack-preloader.rb:161:in `<module:App>'
App 30478 stderr:   from /home/rails/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.44/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>'
App 30478 stderr:   from /home/rails/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.44/helper-scripts/rack-preloader.rb:28:in `<main>'

Cannot submit dynamic selectable parent with form

Would be nice to have an option to submit the parent object with the form, if desired. Using the vehicle example, the vehicle model could reference both the make_id and the model_id. Currently, only the model_id would be submitted to the form.

Turbolinks 5 support

With Turbolinks 5, scripts fired on the initial page load will no longer be re-run when the page is revisited. The coffeescript should be updated to either look for the turbolinks:load event or the listener should be updated to use event delegation.

A more detailed explanation of the issue can be found here.

undefined method `dynamic_selectable

Hi @mattantonelli, i followed your steps and configured the dynamic_selectable but rails spitting out:

undefined method `dynamic_selectable_[#<Gender id: 1, slug: "masculino", gender: "Masculino", created_at: "2015-12-29 20:26:14", updated_at: "2015-12-29 20:26:14">, #<Gender id: 2, slug: "feminino", gender: "Feminino", created_at: "2015-12-29 20:26:23", updated_at: "2015-12-29 20:26:23">, #<Gender id: 3, slug: "infantil", gender: "Infantil", created_at: "2015-12-29 20:26:31", updated_at: "2015-12-29 20:26:31">]_ids_path' for #<#Class:0x007f8904086328:0x007f890991a728>

Support for Rails 5

Looks like a useful gem.... can we please have support for Rails 5? Unsurprisingly, attempting an install as per the README instructions on a Rails 5 project raises dependency errors.

Rails 6

Any plans to make this work in Rails 6?
Right now it won't install the gem because it says it's not compatible with Rails 6.

Convert coffee to JS

The coffee-script dependency can be removed if the jQuery library is converted to JS.

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.