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

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

https://gitlab.com/adamlwalker/spree
Ruby | 75 lines | 61 code | 11 blank | 3 comment | 6 complexity | b37b6b9b1cc83db1f2643f4c472d6c4d MD5 | raw file
  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({ option_values: :option_type }, :product, :default_price, :images, { stock_items: :stock_location })
  25. .ransack(params[:q]).result.page(params[:page]).per(params[:per_page])
  26. respond_with(@variants)
  27. end
  28. def new
  29. end
  30. def show
  31. @variant = scope.includes({ option_values: :option_type }, :option_values, :product, :default_price, :images, { stock_items: :stock_location })
  32. .find(params[:id])
  33. respond_with(@variant)
  34. end
  35. def update
  36. @variant = scope.accessible_by(current_ability, :update).find(params[:id])
  37. if @variant.update_attributes(variant_params)
  38. respond_with(@variant, status: 200, default_template: :show)
  39. else
  40. invalid_resource!(@product)
  41. end
  42. end
  43. private
  44. def product
  45. @product ||= Spree::Product.accessible_by(current_ability, :read).friendly.find(params[:product_id]) if params[:product_id]
  46. end
  47. def scope
  48. if @product
  49. variants = @product.variants_including_master
  50. else
  51. variants = Variant
  52. end
  53. if current_ability.can?(:manage, Variant) && params[:show_deleted]
  54. variants = variants.with_deleted
  55. end
  56. variants.accessible_by(current_ability, :read)
  57. end
  58. def variant_params
  59. params.require(:variant).permit(permitted_variant_attributes)
  60. end
  61. end
  62. end
  63. end
  64. end