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

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

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