RubyOnRails - option_groups_from_collection_for_select and translation of content - ruby-on-rails

I have a collection, I am showing to the user.
But I need to I18n.translate the :key into a readable text from my de.yml.
competences:
key:
compkey001: "Werbung / 360"
compkey001subkey002: "Klassische Werbung / ATL"
compkey002: "Strategie"
f.input :competence_id, label: "Kompetenz", :as => :select,
:collection => option_groups_from_collection_for_select(
#competence_kategories, :competence_unterkats, t(:key,
scope: 'basic_data.competences'), :id, t(:key,
scope: 'basic_data.competences'))
This is not working.
It is giving me an error, something like: t() is not a method.
The below line is working, but showing the keys that are not usable by the user:
f.input :competence_id, label: "Kompetenz", :as => :select,
:collection => option_groups_from_collection_for_select(
#competence_kategories, :competence_unterkats, :key, :id, :key)
Displayed will be:
(bold)compkey001
compkey001subkey001
(bold)compkey002
... etc.
How can I get the translations being displayed in a grouped manner?
Thanks for help!

Related

populate drop down list from array in ruby

I have a country list that I have called in - and have parsed into the following format:
{"Countries"=>[{"Name"=>"ABKHAZIA", "IsoCode"=>"AB", "HasTown"=>"I"}, {"Name"=>"ANGUILLA", "IsoCode"=>"AI", "HasTown"=>"I"}, {"Name"=>"ANTIGUA", "IsoCode"=>"AG", "HasTown"=>"I"}, .... {"Name"=>"ZIMBABWE", "IsoCode"=>"ZW", "HasTown"=>"I"}]}
I want to populate a drop down list with this data. Code I am using to create the drop down box is:
def country_selection_input options = {}
options.reverse_merge!(
:attribute => :country_iso,
:collection => transaction_form.get_countries,
:input_html => {},
:prompt => 'please select',
:label => 'To Where'
)
This gives me a drop down box with a please select prompt and a list that consists of only the one word: Countries.
The data is there - but I am not sure how to get it into the drop down list - and am sure I am missing something simple.
I have tried
:label_method => :Name,
but get an error message of
undefined method `Name' for #<Array:0x007fc385cecbb0>
This will probably turn into a menu as I want to take action based on the country selected - but - this is the first step - getting the list to work.
The answer ended up being
def country_selection_input options = {}
countries = transaction_form.get_countries()[:Countries]
options.reverse_merge!(
:attribute => :country_iso,
:collection => countries,
:label_method => :Name,
:value_method => :IsoCode,
:input_html => {},
:prompt => 'please select',
:label => 'To Where'
)
call_input_from_args_hash options
end

rails radio buttons and adding string to label

I am trying to set up a group of radio buttons in rails using simple_form. The options should come from a map.
In simple form, I saw there the :collection symbol can retrieve a collection (but only an array of arrays and not a hash).
How can I display a radio button collections with custom labels (ideally from a hash)?
Here is what I tried so far. Can I concatenate the symbol with an a string for a label?
#Payment.rb
OPTIONS = [[14, 19], [21,29], [30,39]] #ideally this would be a hash
#new.html.erb
<%= f.input :duration,
:collection => [ [14, 19.to_s], [21,29.to_s], [30,39.to_s] ],
:label_method => :last.concat(" days"),
:value_method => :first,
:as => :radio %>
if I understand your question correctly - you can use lambdas in :label_method. For example:
:label_method => lambda { |a| a.first.to_s + a.last.to_s }

Rails Simple-Form group_method

I came across the following on the simple_form github repo:
f.input :country_id, :collection => #continents, :as => :grouped_select, :group_method => :countries
The thing that caught my attention was the :group_method wich would be exceptionally usefull when creating a selectbox that gives options based on what's in the database. The only thing I can't work out is what kind of input the :group_method expects, and where to put the method.
For instance, I want to create a selectbox for the table column :product_type. I imagine I would write something like this in my simple form:
= f.input :product_type_contains, :collection => #products, :as => :grouped_select, :group_method => :product_types
where :product_type would be the method that is being called. But I don't know what kind of method I should write, what kind of result simple_form expects, and if I should put it in the Product class, Product.rb. Any help would be greatly appreciated!
According to the test suite, simple_form seems to expect the type of arrays or hashes that you would use with grouped_options_for_select:
test 'grouped collection accepts group_label_method option' do
with_input_for #user, :tag_ids, :grouped_select,
:collection => { ['Jose', 'Carlos'] => 'Authors' },
:group_method => :first,
:group_label_method => :last
[...]
test 'grouped collection accepts label and value methods options' do
with_input_for #user, :tag_ids, :grouped_select,
:collection => { 'Authors' => ['Jose', 'Carlos'] },
:group_method => :last,
:label_method => :upcase,
:value_method => :downcase
[...]
Presumably, you could write a class method on Product.rb that creates a structure similar, or even try using grouped_options_for_select(#products)...
Hope this gets you on the right path.

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

Rails — Formtastic, how to set text for options in select?

f.input :some_model_values, :as => :select
Using Formtastic, I need to set a text for options on my select input, but not populated from :some_model_values.
The second:
how could be collection of :some_model_values pre-modefied? Because i don want to show some options according to user role.
Thanks!
What do You mean with "set a text for option on my select input" ?
Please have a look at the :collection parameter, for example:
f.input :some_model_values, :as => :select, :collection => [1,2,3,4]
or
f.input :some_model_values, :as => :select, :collection => [["male",1], ["female",2], ["other",3]]
When you want to set the label, the best option is to localise it by the /config/locales/#locale#.rb file
Hope this helps

Resources