/api/app/controllers/spree/api/v1/taxons_controller.rb

https://gitlab.com/shinvdu/spree · Ruby · 98 lines · 81 code · 15 blank · 2 comment · 9 complexity · 7f7f5a047e0d190afe2326d9f5adc880 MD5 · raw file

  1. module Spree
  2. module Api
  3. module V1
  4. class TaxonsController < Spree::Api::BaseController
  5. def index
  6. if taxonomy
  7. @taxons = taxonomy.root.children
  8. else
  9. if params[:ids]
  10. @taxons = Spree::Taxon.includes(:children).accessible_by(current_ability, :read).where(id: params[:ids].split(','))
  11. else
  12. @taxons = Spree::Taxon.includes(:children).accessible_by(current_ability, :read).order(:taxonomy_id, :lft).ransack(params[:q]).result
  13. end
  14. end
  15. @taxons = @taxons.page(params[:page]).per(params[:per_page])
  16. respond_with(@taxons)
  17. end
  18. def show
  19. @taxon = taxon
  20. respond_with(@taxon)
  21. end
  22. def jstree
  23. show
  24. end
  25. def new
  26. end
  27. def create
  28. authorize! :create, Taxon
  29. @taxon = Spree::Taxon.new(taxon_params)
  30. @taxon.taxonomy_id = params[:taxonomy_id]
  31. taxonomy = Spree::Taxonomy.find_by(id: params[:taxonomy_id])
  32. if taxonomy.nil?
  33. @taxon.errors[:taxonomy_id] = I18n.t(:invalid_taxonomy_id, scope: 'spree.api')
  34. invalid_resource!(@taxon) and return
  35. end
  36. @taxon.parent_id = taxonomy.root.id unless params[:taxon][:parent_id]
  37. if @taxon.save
  38. respond_with(@taxon, status: 201, default_template: :show)
  39. else
  40. invalid_resource!(@taxon)
  41. end
  42. end
  43. def update
  44. authorize! :update, taxon
  45. if taxon.update_attributes(taxon_params)
  46. respond_with(taxon, status: 200, default_template: :show)
  47. else
  48. invalid_resource!(taxon)
  49. end
  50. end
  51. def destroy
  52. authorize! :destroy, taxon
  53. taxon.destroy
  54. respond_with(taxon, status: 204)
  55. end
  56. def products
  57. # Returns the products sorted by their position with the classification
  58. # Products#index does not do the sorting.
  59. taxon = Spree::Taxon.find(params[:id])
  60. @products = taxon.products.ransack(params[:q]).result
  61. @products = @products.page(params[:page]).per(params[:per_page] || 500)
  62. render "spree/api/v1/products/index"
  63. end
  64. private
  65. def taxonomy
  66. if params[:taxonomy_id].present?
  67. @taxonomy ||= Spree::Taxonomy.accessible_by(current_ability, :read).find(params[:taxonomy_id])
  68. end
  69. end
  70. def taxon
  71. @taxon ||= taxonomy.taxons.accessible_by(current_ability, :read).find(params[:id])
  72. end
  73. def taxon_params
  74. if params[:taxon] && !params[:taxon].empty?
  75. params.require(:taxon).permit(permitted_taxon_attributes)
  76. else
  77. {}
  78. end
  79. end
  80. end
  81. end
  82. end
  83. end