PageRenderTime 1635ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

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