PageRenderTime 1389ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/adamlwalker/spree
Ruby | 95 lines | 79 code | 14 blank | 2 comment | 9 complexity | 30ca36b96528aad444dc44ae68f3d928 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 create
  26. authorize! :create, Taxon
  27. @taxon = Spree::Taxon.new(taxon_params)
  28. @taxon.taxonomy_id = params[:taxonomy_id]
  29. taxonomy = Spree::Taxonomy.find_by(id: params[:taxonomy_id])
  30. if taxonomy.nil?
  31. @taxon.errors[:taxonomy_id] = I18n.t(:invalid_taxonomy_id, scope: 'spree.api')
  32. invalid_resource!(@taxon) and return
  33. end
  34. @taxon.parent_id = taxonomy.root.id unless params[:taxon][:parent_id]
  35. if @taxon.save
  36. respond_with(@taxon, status: 201, default_template: :show)
  37. else
  38. invalid_resource!(@taxon)
  39. end
  40. end
  41. def update
  42. authorize! :update, taxon
  43. if taxon.update_attributes(taxon_params)
  44. respond_with(taxon, status: 200, default_template: :show)
  45. else
  46. invalid_resource!(taxon)
  47. end
  48. end
  49. def destroy
  50. authorize! :destroy, taxon
  51. taxon.destroy
  52. respond_with(taxon, status: 204)
  53. end
  54. def products
  55. # Returns the products sorted by their position with the classification
  56. # Products#index does not do the sorting.
  57. taxon = Spree::Taxon.find(params[:id])
  58. @products = taxon.products.ransack(params[:q]).result
  59. @products = @products.page(params[:page]).per(params[:per_page] || 500)
  60. render "spree/api/v1/products/index"
  61. end
  62. private
  63. def taxonomy
  64. if params[:taxonomy_id].present?
  65. @taxonomy ||= Spree::Taxonomy.accessible_by(current_ability, :read).find(params[:taxonomy_id])
  66. end
  67. end
  68. def taxon
  69. @taxon ||= taxonomy.taxons.accessible_by(current_ability, :read).find(params[:id])
  70. end
  71. def taxon_params
  72. if params[:taxon] && !params[:taxon].empty?
  73. params.require(:taxon).permit(permitted_taxon_attributes)
  74. else
  75. {}
  76. end
  77. end
  78. end
  79. end
  80. end
  81. end