Adding a value-dependent data attribute to a simple_form checkbox collection - ruby-on-rails

I'm generating a list of checkboxes for a single collection like so:
= f.input :parts, as:check_boxes, collection: #parts_list
I want some checkboxes in the collection to disappear/reappear depending on the value of a select widget higher up in the form. (e.g. choosing "Tracker Robot" from the Robot select means that the "Legs" part checkbox disappears and the "Wheels" checkbox appears, etc.)
What I'd like to do is attach a computed data attribute to each individual Part checkbox, with the attribute value listing the Robots that can use that Part; then some JS will do the work of hiding/showing the checkboxes. However, I don't know how I can generate those data attributes using simple_form.
I would normally create a custom "parts" input, but there seems to be a problem with making custom collection inputs; it looks for a named method (collection_parts) inside form_builder.rb, which won't exist, and if I try and extend the FormBuilder it sends me down a major rabbit hole.
I could write some JS to load the data attrs into the generated HTML, but then I have to generate custom JS based on my Rails data, and that feels like the wrong way to do it.

Let's assume that the form is for Order model and you are changing the parts collection based on the value of a field called region.
Update the form view. Specify the id for form, region field and parts field.
= simple_form_for(#order, :html => { :id => "order-form"}) do |f|
= f.input :region, :wrapper_html => { :id => "order-form-region", |
"data-parts-url" => parts_orders_path(:id => #order.id, :region => #order.region)} |
= f.input :parts, as: check_boxes, collection: #parts_list, |
:wrapper_html => { id' => 'parts-check-box-list'} |
Add a new action called parts in the route.rb file.
resources :orders do
collection do
get :parts
end
end
Add the new action to your controller
class OrdersController < ApplicationController
# expects id and region as parameters
def parts
#order = params[:id].present? ? Order.find(params[:id]) : Order.new
#parts_list = Part.where(:region => params[:region])
end
end
Add a helper
def parts_collection(order, parts_list)
"".tap do |pc|
# to generate the markup for collection we need a dummy form
simple_form_for(order) do |f|
pc << f.input(:parts, as: check_boxes, collection: parts_list,
:wrapper_html => {:id => 'parts-check-box-list'})
end
end
end
Add a js view for the action (orders/parts.js.erb)
$('#parts-check-box-list').replaceWith('<%= j(parts_collection(#order, #parts_list)) %>');
Register data change event handlers for region field in your application.js
$(document).ready(function() {
$('#order-form').on("change", "#order-form-region", function () {
// Access the data-parts-url set in the region field to submit JS request
$.getScript($(this).attr('data-parts-url'));
});
});

I think you can do it like this:
= f.input :parts do
= f.collection_check_boxes :parts, #parts_list, :id, :to_s, item_wrapper_tag: :label, item_wrapper_class: :checkbox do |b|
- b.check_box(data: { YOUR DATA ATTRIBUTES HERE }) + b.text

this may be simpler.
Assumptions
#robots - an array containing the list of robots
#parts - a hash containing a list of parts for each robot
Sample Code
# controller
#robots = %w[tracker nontracker]
#parts = { tracker: %w[wheels lcd resistor], nontracker: %w[lcd resistor] }
# view
= f.input :robots, as: :select, collection: #robots, input_html: { id: 'robot-select' }
#parts-list
:javascript
var parts = #{#parts.to_json};
$(document).ready(function() {
$('#robot-select').change(function() {
$('#parts-list').html('');
$(parts[$(this).val()]).each(function(index, text) {
$('#parts-list').append('<input type="checkbox" value=' + text + '>' + text + '</input>')
})
})
})
you can see this working if you clone https://github.com/jvnill/simple_form_search_app and go to /robots

Some input options in SimpleForm accept a lambda that gets called for every item in a collection:
f.input :role_ids, :collection => (1..10).to_a,
:label_method => :to_i, :value_method => :to_i,
:as => :check_boxes, :required=> true,
:disabled => ->(item){ item.even? }
but input_html doesn't seem to be one of them.
The solution is probably to create a custom SimpleForm collection input that applies the data attributes itself. Not as flexible perhaps, but I think this is the only way to go for now.
There's a tutorial page on GitHub that should get you started.

Related

Rails:how to show name instead of ID or Address in has_many relation in active_admin?

These days I'm using the active_admin to manage my data. I have a Audio model and Problem model. Audio has many problems and Problem belongs to audio.
I use the active_admin to create the problems. But in the problem's new page, there is a drop-down list shows the content like:
#<Audio:0xb4116084>
With the address I can hardly recognize which file I want. What I want to show in the Audio's drop-down list is the Audio's title which is a column of Audio model. I just want to change this column in the new page, and others remain the same as default. What should I do? Thanks!
Audio class must implement display_name method
Ex
class Audio
def display_name
title
end
end
this is from active admin sources
# Active Admin makes educated guesses when displaying objects, this is
# the list of methods it tries calling in order
setting :display_name_methods, [ :display_name,
:full_name,
:name,
:username,
:login,
:title,
:email,
:to_s ]
Looks like you haven't such methods so to_s is called for Audio objects
You can use a :member_label.
Here is a example
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :problems,
:input_html => { :multiple => false, :style => "width: 700px;"},
:collection => Audio.all,
:member_label => :audio_name
end

What is the Rails convention for sending form data to a URL dependent on form value?

I would like a form submitted at the url
/index/fruit
to submit the form data to
/index/:identifier
where :identifier is determined by a value of the form
What is the rails convention in this instance?
Is there a way to achieve this without a controller level redirect or javascript-updating the submit URL?
routes.rb
match 'smasher(/:action(/:id))', :controller => "customcontroller", :as => :smasher, :defaults => { :action => :index, :id => :fruit }
index.html.erb
<%= semantic_form_for :d, :url => smasher_path, :html => { :method => :get } do |f| %>
... form data ...
<%= f.input :identifier, :as => :hidden %>
<% end %>
My current implementation is similar to this answer
There's isn't really a "convention" for this, but rather one of those things where there's more than one way to do it.
One way that you could do it is still send the form to one and only one action within the controller, but then delegate in the controller which action to go to, like this:
def smasher
if params[:identifier] == 'this'
smash_this!
else
smash_that!
end
end
def smash_this!
# code goes here
end
def smash_that!
# code goes here
end
Heres the javascript version (though technically its all on an erb html template), if you're feeling up to it.
<%= f.input :identifier, :as => :hidden, :onchange => "$(this).setAction()" %>
<script>
// While you can this script block here within your erb template
// but best practice says you should have it included somehow within `<head></head>`
$(function() {
//create a method on the Jquery Object to adjust the action of the form
$.fn.setAction = function() {
var form = $(this).parents('form').first();
var action = form.attr('action')
form.attr('action', action.substr( 0, action.lastIndexOf('/')+1 ) + $(this).val());
}
});
</script>
Heres the pure javascript version:
$(function() {
//create a method on the Jquery Object to adjust the action of the form
$.fn.setAction = function() {
var form = $(this).parents('form').first();
var action = form.attr('action')
form.attr('action', action.substr( 0, action.lastIndexOf('/')+1 ) + $(this).val());
}
//we gotta bind the onchange here
$('input[name="identifier"]').change($.fn.setAction);
});

Manipulating tags with acts_as_taggable_on and ActiveAdmin

I have a Post model which I'm accessing through ActiveAdmin. It's also taggable using the acts_as_taggable_on gem. So the admin can add, edit or delete tags from a specific Post.
The normal way to add the tagging functionality for the resource in your admin panel is by doing this in admin/posts.rb:
ActiveAdmin.register Post do
form do |f|
f.inputs "Details", :multipart => true do
f.input :tag_list
# and the other irrelevant fields goes here
end
f.buttons
end
end
However, I want to have the tags selected from a multiple select form field and not being entered manually in a text field (like it is with the code above). So I've tried doing this:
f.input :tag_list, :as => :select,
:multiple => :true,
:collection => ActsAsTaggableOn::Tag.all
but it doesn't work as expected. This actually creates new tags with some integer values for names and assigns them to that Post. Someone told me that extra code is needed for this to work.
Any clues on how this is done? Here's my model just in case: http://pastie.org/3911123
Thanks in advance.
Instead of
:collection => ActsAsTaggableOn::Tag.all
try
:collection => ActsAsTaggableOn::Tag.pluck(:name)
Setting the collection to Tag.all is going to tag your posts with the tag's ID, since that's how tags are identified by default (that's where the integer values for names are coming from). map(&:name) tells the form builder to use the tag's name instead.

Active Admin - refresh second drop down based on first drop down, Ruby on Rails

I am using Active Admin Gem on Ruby on Rails. I have a form in which i have selected category and sub category and then accordingly i have to fill the data. So i created two tables in sqlite added in active admin resouce.
Every thing is working fine but the drop down of sub category is not getting filtered based on the category choosen.
I am new to Ruby and RoR too. I don't know how to refresh dropdown of the subcategory after selecting category.
I know i can do it from AJAX and javascript but i dont know where to code for that?
Also, is there any specific filter avaliable in Active Admin which will make it happen without ajax or javascript.
Any ideas or help will be highly appreciated.
i don't know if there is any specific filter avaliable in Active Admin, but i solved it in this 3-steps way (assuming category - is a house, subcategory - is a flat):
1-st step: define helper containing ajax request
(of course, you have to predefine path in routes.rb)
#application_helper.rb
def remote_request(type, path, params={}, target_tag_id)
"$.#{type}('#{path}',
{#{params.collect { |p| "#{p[0]}: #{p[1]}" }.join(", ")}},
function(data) {$('##{target_tag_id}').html(data);}
);"
end
2-nd step: add this method for :onchange action
#admin/inhabitants.rb (DSL with formtastic)
form do |f|
f.inputs do
#...
f.input :house, :input_html => {
:onchange => remote_request(:post, :change_flats, {:house_id=>"$('#house_id').val()"}, :flat_id)
}
f.input :flat
#...
end
end
3-rd step: render result of filtering
(you can render partial instead of :text, I decided leave it in one activeadmin resource file )
controller do
def change_flats
#flats = House.find_by_id(params[:house_id]).try(:flats)
render :text=>view_context.options_from_collection_for_select(#flats, :id, :flat_number)
end
end
I accomplished this as any non-rails developer working on a rails project would - quick and dirty. Here's how:
#...
f.input :user, :input_html => {
:onchange => "
var user = $(this).val();
$('#order_location_id').val(0).find('option').each(function(){
var $option = $(this),
isCorrectUser = ($option.attr('data-user') === user);
$option.prop('disabled',!isCorrectUser);
});
"
}
f.input :location, collection: Location.all.map{ |loc|
[loc.name,loc.id, {"data-user" => loc.user_id}]
}
#...
No AJAX required. Note that this does not remove the unwanted options, it just disables them (sufficient for my scenario). This could easily be made modular with a helper, but I really only needed the functionality once.
For anyone else wrestling with the same problem, look at this railscast
I faced the same problem here
here's how I implemented multiple dynamic select menus in activeadmin:
config/initializers/active_admin.rb
config.register_javascript 'exam_registrations.js.coffee'
app/admin/exam_registrations.rb
form do |f|
f.inputs "Exam Registration Details" do
f.input :user_id, :label => 'Teacher', :as => :select, :collection => User.where(:admin => 'false', :active => true).order(:name), :include_blank => true
f.input :student_id, :hint => 'Students grouped by teacher names', :as => :select, :collection => option_groups_from_collection_for_select(User.where(:admin => false, :active => true).order(:name), :students, :name, :id, :name)
f.input :lesson_id, :hint => 'Lessons grouped by student names', :as => :select, :collection => option_groups_from_collection_for_select(Student.where(:active => true).order(:name), :lessons, :name, :id, :name)
end
f.buttons
end
app/assets/javascripts/exam_registrations.js.coffee
#first menu
jQuery ->
$('#exam_registration_student_id').parent().hide()
students = $('#exam_registration_student_id').html()
$('#exam_registration_user_id').change ->
user = $('#exam_registration_user_id :selected').text()
escaped_user = user.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g, '\\$1')
options = $(students).filter("optgroup[label='#{escaped_user}']").html()
if options
$('#exam_registration_student_id').html(options)
$('#exam_registration_student_id').parent().show()
else
$('#exam_registration_student_id').empty()
$('#exam_registration_lesson_id').empty()
# second menu
$('#exam_registration_lesson_id').parent().hide()
lessons = $('#exam_registration_lesson_id').html()
$('#exam_registration_student_id').click ->
student = $('#exam_registration_student_id :selected').text()
escaped_student = student.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g, '\\$1')
options = $(lessons).filter("optgroup[label='#{escaped_student}']").html()
if options
$('#exam_registration_lesson_id').html(options)
$('#exam_registration_lesson_id').parent().show()
else
$('#exam_registration_lesson_id').empty()
restart the server and the menus work!
Now it's possible with this gem https://github.com/holyketzer/activeadmin-ajax_filter, use in you form code like this:
f.input :category_id, as: :select # ...
f.input :subcategory_id, as: :ajax_select, data: {
ajax_search_fields: [:category_id],
search_fields: [:subcategory_atrribute],
url: '/admin/subcategories/filter'
}
And in you subcategory resource page:
ActiveAdmin.register Subcategory do
include ActiveAdmin::AjaxFilter
# ...
end
don't forget to include assets
You can also use activeadmin_addons gem Nested Select
dependent-select could be also a good option

Deleting a Paperclip Attachment in Activeadmin

I'm using paperclip to add image attachments to several models and Activeadmin to provide a simple admin interface.
I have this code in my activeadmin model file which allows for image uploads:
form :html => { :enctype => "multipart/form-data"} do |f|
f.inputs "Details" do
f.input :name
f.input :subdomain
end
f.inputs "General Customisation" do
f.input :standalone_background, :hint => (("current image:<br/>").html_safe + f.template.image_tag(f.object.standalone_background.url(:thumb))).html_safe, :as => :file
end
end
which works fine. All of the images I'm attaching like this are optional and so I'd like to give the user the option to remove a previously added image but can't work out how to do this in Activeadmin. All of the example I've seen are for situations where the attachments are managed through a separate has_many association rather than being part of the main model.
Does anyone know of a way to do this?
In your active admin view
form :html => { :enctype => "multipart/form-data"} do |f|
f.inputs "Details" do
f.input :name
f.input :subdomain
end
f.inputs "General Customisation" do
f.input :standalone_background, :hint => (("current image:<br/>").html_safe + f.template.image_tag(f.object.standalone_background.url(:thumb))).html_safe, :as => :file
f.input :remove_standalone_background, as: :boolean, required: false, label: "remove standalone background"
end
end
In your model
You could define a status flag like bellow
attr_writer :remove_standalone_background
def remove_standalone_background
#remove_standalone_background || false
end
OR (depreciated in rails 3.2)
attr_accessor_with_default : standalone_background,false
before_save :before_save_callback
And
def before_save_callback
if self.remove_standalone_background
self.remove_standalone_background=nil
end
end
You could implement this by creating a custom method. This can be done
member_action :custom_action, :method => :get do
//code
end
Also you should add a custom column with a link such as
index do
column "Custom" do |item|
link_to "Custom action", "/admin/items/custom_action"
end
end
Another option is to have a status flag for the attachment or image. Before saving the edited object, you unlink the image.
Thank you for your help guys. This is the final working code...
admin/product.rb
f.input :image, required: false, hint: (("Current image:<br/>").html_safe + f.template.image_tag(f.object.image.url(:thumb))).html_safe
f.input :remove_image, as: :boolean, required: false, label: "Remove Image"
models/product.rb
attr_writer :remove_image
def remove_image
#remove_image || false
end
before_validation { self.image.clear if self.remove_image == '1' }
Although accepts_nested_attributes_for(:foo, allow_destroy: true) only works with ActiveRecord associations like belongs_to we can borrow from its design to have paperclip attachment deletion work in a similar way.
(To understand how nested attributes work in Rails see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html).
Add a <attachment_name>_attributes= writer method like below to your model that already uses has_attached_file:
has_attached_file :standalone_background
def standalone_background_attributes=(attributes)
# Marks the attachment for destruction on next save,
# if the attributes hash contains a _destroy flag
# and a new file was not uploaded at the same time:
if has_destroy_flag?(attributes) && !standalone_background.dirty?
standalone_background.clear
end
end
The <attachment_name>_attributes= method calls Paperclip::Attachment#clear to mark the attachment for destruction when the model is next saved.
Next open the existing app/admin/your_model_here.rb file (use the correct file path for your app) and setup strong parameters to permit the _destroy flag nested attribute on <attachment_name>_attributes:
ActiveAdmin.register YourModelHere do
permit_params :name, :subdomain,
:standalone_background,
standalone_background_attributes: [:_destroy]
In the same file, add a nested _destroy checkbox to the ActiveAdmin form block. This checkbox must be nested within <attachment_name>_attributes using semantic_fields_for (or one of the other nested attributes methods provided by formtastic).
form :html => { :enctype => "multipart/form-data"} do |f|
f.inputs "Details" do
...
end
f.inputs "General Customisation" do
...
if f.object.standalone_background.present?
f.semantic_fields_for :standalone_background_attributes do |fields|
fields.input :_destroy, as: :boolean, label: 'Delete?'
end
end
end
end
Your form should now show a delete checkbox when there is an attachment present. Checking this checkbox and submitting a valid form ought to delete the attachment.
Source: https://github.com/activeadmin/activeadmin/wiki/Deleting-Paperclip-Attachments-with-ActiveAdmin

Resources