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

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

http://github.com/spree/spree
Ruby | 95 lines | 79 code | 14 blank | 2 comment | 8 complexity | f038b69ef1bc7a5ab430322408b90a7e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. module Spree
  2. module Api
  3. module V1
  4. class TaxonsController < Spree::Api::BaseController
  5. def index
  6. @taxons = if taxonomy
  7. taxonomy.root.children
  8. elsif params[:ids]
  9. Spree::Taxon.includes(:children).accessible_by(current_ability).where(id: params[:ids].split(','))
  10. else
  11. Spree::Taxon.includes(:children).accessible_by(current_ability).order(:taxonomy_id, :lft)
  12. end
  13. @taxons = @taxons.ransack(params[:q]).result
  14. @taxons = @taxons.page(params[:page]).per(params[:per_page])
  15. respond_with(@taxons)
  16. end
  17. def show
  18. @taxon = taxon
  19. respond_with(@taxon)
  20. end
  21. def jstree
  22. show
  23. end
  24. def new; 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.add(:taxonomy_id, I18n.t('spree.api.invalid_taxonomy_id'))
  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(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, :show).find(params[:taxonomy_id])
  66. end
  67. end
  68. def taxon
  69. @taxon ||= taxonomy.taxons.accessible_by(current_ability, :show).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