Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. class AlbumFormBuilder < SimpleForm::FormBuilder
  2.  
  3. def polymorphic(association, options={})
  4. options = options.dup
  5.  
  6. raise ArgumentError, "Association cannot be used in forms not associated with an object" unless @object
  7. raise ArgumentError, "You need to pass types for select" unless options[:types]
  8.  
  9. reflection = find_association_reflection(association)
  10. raise "Association #{association.inspect} not found" unless reflection
  11. @association = association
  12.  
  13. # Convert symbols into constants
  14. types = options.delete(:types).map {|type| type.to_s.classify.constantize }
  15. types_options = {
  16. as: :select,
  17. collection: types.map {|klass| [klass.model_name.human, klass.to_s] },
  18. input_html: { class: "js-polymorphic-type" }
  19. }
  20.  
  21. # Get records for select tags
  22. @attribute = (reflection.respond_to?(:options) && reflection.options[:foreign_key]) || :"#{reflection.name}_id"
  23. collections ||= options.fetch(:collections) {
  24. types.reduce({}) do |h, klass|
  25. h[klass.to_s] = collection(klass)
  26. h
  27. end
  28. }
  29. collection_options = {
  30. class: "select form-control",
  31. include_blank: true
  32. }
  33.  
  34. # Render tags
  35. out = ""
  36. out << input("#{association}_type", types_options)
  37. out << template.content_tag(:div, class: "form-group form-polymorphic-select js-polymorphic-select") do
  38. collections.map do |type, collection|
  39. template.select_tag("#{type.downcase}_id", select_options(collection, type), collection_options.dup)
  40. end.join.html_safe
  41. end
  42. out.html_safe
  43. end
  44.  
  45. private
  46.  
  47. def collection(klass)
  48. klass.pluck(:title, :id)
  49. end
  50.  
  51. def select_options(collection, type)
  52. template.options_for_select collection, selected?(type)
  53. end
  54.  
  55. def selected?(type)
  56. object.send("#{@association}_type") == type && object.send(@attribute)
  57. end
  58.  
  59. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement