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

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

http://github.com/spree/spree
Ruby | 81 lines | 65 code | 13 blank | 3 comment | 6 complexity | 590b702ed909cfbce8291d98dc7ed2c7 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. module Spree
  2. module Api
  3. module V1
  4. class VariantsController < Spree::Api::BaseController
  5. before_action :product
  6. def create
  7. authorize! :create, Variant
  8. @variant = scope.new(variant_params)
  9. if @variant.save
  10. respond_with(@variant, status: 201, default_template: :show)
  11. else
  12. invalid_resource!(@variant)
  13. end
  14. end
  15. def destroy
  16. @variant = scope.accessible_by(current_ability, :destroy).find(params[:id])
  17. @variant.destroy
  18. respond_with(@variant, status: 204)
  19. end
  20. # The lazyloaded associations here are pretty much attached to which nodes
  21. # we render on the view so we better update it any time a node is included
  22. # or removed from the views.
  23. def index
  24. @variants = scope.includes(*variant_includes).for_currency_and_available_price_amount.
  25. ransack(params[:q]).result.page(params[:page]).per(params[:per_page])
  26. respond_with(@variants)
  27. end
  28. def new; end
  29. def show
  30. @variant = scope.includes(*variant_includes).find(params[:id])
  31. respond_with(@variant)
  32. end
  33. def update
  34. @variant = scope.accessible_by(current_ability, :update).find(params[:id])
  35. if @variant.update(variant_params)
  36. respond_with(@variant, status: 200, default_template: :show)
  37. else
  38. invalid_resource!(@product)
  39. end
  40. end
  41. private
  42. def product
  43. if params[:product_id]
  44. @product ||= Spree::Product.accessible_by(current_ability, :show).
  45. friendly.find(params[:product_id])
  46. end
  47. end
  48. def scope
  49. variants = if @product
  50. @product.variants_including_master
  51. else
  52. Variant
  53. end
  54. if current_ability.can?(:manage, Variant) && params[:show_deleted]
  55. variants = variants.with_deleted
  56. end
  57. variants.eligible.accessible_by(current_ability)
  58. end
  59. def variant_params
  60. params.require(:variant).permit(permitted_variant_attributes)
  61. end
  62. def variant_includes
  63. [{ option_values: :option_type }, :product, :default_price, :images, { stock_items: :stock_location }]
  64. end
  65. end
  66. end
  67. end
  68. end