Module: RESTFramework::Controller
- Defined in:
- lib/rest_framework/controller.rb,
lib/rest_framework/controller/bulk.rb,
lib/rest_framework/controller/crud.rb,
lib/rest_framework/controller/openapi.rb
Overview
This module provides the common functionality for all REST controllers. The implementation is split across several files under ‘controller/` for readability; each of those files reopens this module rather than defining a separate submodule.
Defined Under Namespace
Modules: ClassMethods
Constant Summary collapse
- RRF_BASE_CONFIG =
{ extra_actions: nil, extra_member_actions: nil, singleton_controller: nil, # Options related to metadata and display. title: nil, description: nil, version: nil, inflect_acronyms: RESTFramework.config.inflect_acronyms, openapi_include_children: false, # Core attributes related to models. model: nil, recordset: nil, excluded_actions: nil, bulk: false, # Attributes for configuring record fields. fields: nil, field_config: nil, read_only_fields: RESTFramework.config.read_only_fields, write_only_fields: RESTFramework.config.write_only_fields, hidden_fields: nil, # Attributes for finding records. find_by_fields: nil, find_by_query_param: "find_by".freeze, # Options for what should be included/excluded from default fields. exclude_associations: false, # Options for handling request body parameters. allowed_parameters: nil, # Attributes for the default native serializer. native_serializer_config: nil, native_serializer_singular_config: nil, native_serializer_plural_config: nil, native_serializer_only_query_param: "only".freeze, native_serializer_except_query_param: "except".freeze, native_serializer_include_query_param: "include".freeze, native_serializer_exclude_query_param: "exclude".freeze, native_serializer_associations_limit: nil, native_serializer_associations_limit_query_param: "associations_limit".freeze, native_serializer_include_associations_count: false, # Attributes for filtering, ordering, and searching. filter_backends: [ RESTFramework::QueryFilter, RESTFramework::OrderingFilter, RESTFramework::SearchFilter, ].freeze, filter_recordset_before_find: true, filter_fields: nil, ordering_fields: nil, ordering_query_param: "ordering".freeze, ordering_no_reorder: false, search_fields: nil, search_query_param: "search".freeze, search_ilike: false, ransack_options: nil, ransack_query_param: "q".freeze, ransack_distinct: true, ransack_distinct_query_param: "distinct".freeze, # Options for association assignment. permit_id_assignment: true, permit_nested_attributes_assignment: true, # Option for `recordset.create` vs `Model.create` behavior. create_from_recordset: true, # Options related to serialization. rescue_unknown_format_with: :json, serializer_class: nil, serialize_to_json: true, serialize_to_xml: true, # Options related to pagination. paginator_class: nil, page_size: 20, page_query_param: "page", page_size_query_param: "page_size", max_page_size: nil, # Option to disable serializer adapters by default, mainly introduced because Active Model # Serializers will do things like serialize `[]` into `{"":[]}`. disable_adapters_by_default: true, # Custom integrations (reduces serializer performance due to method calls). enable_action_text: false, enable_active_storage: false, }
- BASE64_REGEX =
/data:(.*);base64,(.*)/- BASE64_TRANSLATE =
->(field, value) { return value unless BASE64_REGEX.match?(value) _, content_type, payload = value.match(BASE64_REGEX).to_a { io: StringIO.new(Base64.decode64(payload)), content_type: content_type, filename: "file_#{field}#{Rack::Mime::MIME_TYPES.invert[content_type]}", } }
- ACTIVESTORAGE_KEYS =
[ :io, :content_type, :filename, :identify, :key ]
Class Method Summary collapse
Instance Method Summary collapse
-
#bulk_serialize(records) ⇒ Object
Serialize the records, but also include any errors that might exist.
- #create ⇒ Object
-
#create! ⇒ Object
Perform the ‘create!` call and return the created record.
-
#create_all! ⇒ Object
Perform the ‘create` call, and return the collection of (possibly) created records.
-
#create_from ⇒ Object
Determine what collection to call ‘create` on.
- #destroy ⇒ Object
-
#destroy! ⇒ Object
Perform the ‘destroy!` call and return the destroyed (and frozen) record.
- #destroy_all ⇒ Object
-
#destroy_all! ⇒ Object
Perform the ‘destroy!` call and return the destroyed (and frozen) record.
-
#get_allowed_parameters ⇒ Object
Get a hash of strong parameters for the current action.
-
#get_body_params(bulk_mode: nil) ⇒ Object
(also: #get_create_params, #get_update_params)
Use strong parameters to filter the request body.
- #get_fields ⇒ Object
-
#get_index_records ⇒ Object
Get records with both filtering and pagination applied.
-
#get_record ⇒ Object
Get a single record by primary key or another column, if allowed.
-
#get_records ⇒ Object
Filter the recordset and return records this request has access to.
-
#get_recordset ⇒ Object
Get the set of records this controller has access to.
- #get_serializer_class ⇒ Object
- #index ⇒ Object
- #openapi_document ⇒ Object
- #options ⇒ Object
-
#render_api(payload, **kwargs) ⇒ Object
(also: #api_response)
Render a browsable API for ‘html` format, along with basic `json`/`xml` formats, and with support or passing custom `kwargs` to the underlying `render` calls.
-
#root ⇒ Object
Default action for API root.
- #route_groups ⇒ Object
- #rrf_error_handler(e) ⇒ Object
-
#serialize(data, **kwargs) ⇒ Object
Serialize the given data using the ‘serializer_class`.
- #show ⇒ Object
- #update ⇒ Object
-
#update! ⇒ Object
Perform the ‘update!` call and return the updated record.
- #update_all ⇒ Object
-
#update_all! ⇒ Object
Perform the ‘update` call and return the collection of (possibly) updated records.
Class Method Details
.included(base) ⇒ Object
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/rest_framework/controller.rb', line 395 def self.included(base) return unless base.is_a?(Class) base.extend(ClassMethods) # By default, the layout should be set to `rest_framework`. base.layout("rest_framework") # Add class attributes unless they already exist. RRF_BASE_CONFIG.each do |a, default| next if base.respond_to?(a) # Don't leak class attributes to the instance to avoid conflicting with action methods. base.class_attribute(a, default: default, instance_accessor: false) end # Alias `extra_actions` to `extra_collection_actions`. unless base.respond_to?(:extra_collection_actions) base.singleton_class.alias_method(:extra_collection_actions, :extra_actions) base.singleton_class.alias_method(:extra_collection_actions=, :extra_actions=) end # Skip CSRF since this is an API. begin base.skip_before_action(:verify_authenticity_token) rescue nil end # Handle some common exceptions. unless RESTFramework.config.disable_rescue_from base.rescue_from( ActionController::ParameterMissing, ActionController::UnpermittedParameters, ActionDispatch::Http::Parameters::ParseError, ActiveRecord::AssociationTypeMismatch, ActiveRecord::NotNullViolation, ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, ActiveRecord::RecordNotDestroyed, ActiveRecord::RecordNotUnique, ActiveModel::UnknownAttributeError, with: :rrf_error_handler, ) end # Use `TracePoint` hook to automatically call `rrf_finalize`. if RESTFramework.config.auto_finalize # :nocov: TracePoint.trace(:end) do |t| next if base != t.self base.rrf_finalize # It's important to disable the trace once we've found the end of the base class definition, # for performance. t.disable end # :nocov: end end |
Instance Method Details
#bulk_serialize(records) ⇒ Object
Serialize the records, but also include any errors that might exist. This is used for bulk actions, however we include it here so the helper is available everywhere.
4 5 6 7 8 9 10 11 12 |
# File 'lib/rest_framework/controller/bulk.rb', line 4 def bulk_serialize(records) # This is kinda slow, so perhaps we should eventually integrate `errors` serialization into # the serializer directly. This would fail for active model serializers, but maybe we don't # care? s = RESTFramework::Utils.wrap_ams(self.get_serializer_class) records.map do |record| s.new(record, controller: self).serialize.merge!({ errors: record.errors.presence }.compact) end end |
#create ⇒ Object
2 3 4 5 6 7 8 9 10 |
# File 'lib/rest_framework/controller/crud.rb', line 2 def create # Bulk create: if `bulk` is enabled and the request body is an array, delegate to `create_all!`. if self.class.bulk && params[:_json].is_a?(Array) records = self.create_all! return render(api: self.bulk_serialize(records)) end render(api: self.create!, status: :created) end |
#create! ⇒ Object
Perform the ‘create!` call and return the created record.
13 14 15 |
# File 'lib/rest_framework/controller/crud.rb', line 13 def create! self.create_from.create!(self.get_create_params) end |
#create_all! ⇒ Object
Perform the ‘create` call, and return the collection of (possibly) created records.
15 16 17 18 19 20 |
# File 'lib/rest_framework/controller/bulk.rb', line 15 def create_all! create_data = self.get_create_params(bulk_mode: true)[:_json] # Perform bulk create in a transaction. ActiveRecord::Base.transaction { self.create_from.create(create_data) } end |
#create_from ⇒ Object
Determine what collection to call ‘create` on.
789 790 791 792 793 794 795 796 797 798 799 |
# File 'lib/rest_framework/controller.rb', line 789 def create_from if self.class.create_from_recordset # Create with any properties inherited from the recordset. We exclude any `select` clauses # in case model callbacks need to call `count` on this collection, which typically raises a # SQL `SyntaxError`. self.get_recordset.except(:select) else # Otherwise, perform a "bare" insert_all. self.class.model end end |
#destroy ⇒ Object
57 58 59 60 |
# File 'lib/rest_framework/controller/crud.rb', line 57 def destroy self.destroy! render(api: "") end |
#destroy! ⇒ Object
Perform the ‘destroy!` call and return the destroyed (and frozen) record.
63 64 65 |
# File 'lib/rest_framework/controller/crud.rb', line 63 def destroy! self.get_record.destroy! end |
#destroy_all ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/rest_framework/controller/bulk.rb', line 42 def destroy_all if params[:_json].is_a?(Array) records = self.destroy_all! serialized_records = self.bulk_serialize(records) return render(api: serialized_records) end render( api: { message: "Bulk destroy requires an array of primary keys as input." }, status: 400, ) end |
#destroy_all! ⇒ Object
Perform the ‘destroy!` call and return the destroyed (and frozen) record.
55 56 57 58 59 60 61 |
# File 'lib/rest_framework/controller/bulk.rb', line 55 def destroy_all! pk = self.class.model.primary_key destroy_data = self.request.request_parameters[:_json] # Perform bulk destroy in a transaction. ActiveRecord::Base.transaction { self.get_recordset.where(pk => destroy_data).destroy_all } end |
#get_allowed_parameters ⇒ Object
Get a hash of strong parameters for the current action.
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 |
# File 'lib/rest_framework/controller.rb', line 576 def get_allowed_parameters return @_get_allowed_parameters if defined?(@_get_allowed_parameters) @_get_allowed_parameters = self.class.allowed_parameters return @_get_allowed_parameters if @_get_allowed_parameters # Assemble strong parameters. variations = [] hash_variations = {} reflections = self.class.model.reflections @_get_allowed_parameters = self.get_fields.map { |f| f = f.to_s config = self.class.field_configuration[f] # ActionText Integration: if self.class.enable_action_text && reflections.key?("rich_text_#{f}") next f end # ActiveStorage Integration: `has_one_attached` if self.class.enable_active_storage && reflections.key?("#{f}_attachment") hash_variations[f] = ACTIVESTORAGE_KEYS next f end # ActiveStorage Integration: `has_many_attached` if self.class.enable_active_storage && reflections.key?("#{f}_attachments") hash_variations[f] = ACTIVESTORAGE_KEYS next nil end if config[:reflection] # Add `_id`/`_ids` variations for associations. if id_field = config[:id_field] if id_field.ends_with?("_ids") hash_variations[id_field] = [] else variations << id_field end end # Add `_attributes` variations for associations. # TODO: Consider adjusting this based on `nested_attributes_options`. if self.class.permit_nested_attributes_assignment hash_variations["#{f}_attributes"] = ( config[:sub_fields] + [ "_destroy" ] ) end # Associations are not allowed to be submitted in their bare form (if they are submitted # that way, they will be translated to either id/ids or nested attributes assignment). next nil end next f }.compact @_get_allowed_parameters += variations @_get_allowed_parameters << hash_variations @_get_allowed_parameters end |
#get_body_params(bulk_mode: nil) ⇒ Object Also known as: get_create_params, get_update_params
Use strong parameters to filter the request body.
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 |
# File 'lib/rest_framework/controller.rb', line 639 def get_body_params(bulk_mode: nil) data = self.request.request_parameters pk = self.class.model&.primary_key allowed_params = self.get_allowed_parameters # Before we filter the data, dynamically dispatch association assignment to either the id/ids # assignment ActiveRecord API or the nested assignment ActiveRecord API. Note that there is no # need to check for `permit_id_assignment` or `permit_nested_attributes_assignment` here, since # that is enforced by strong parameters generated by `get_allowed_parameters`. self.class.model.reflections.each do |name, ref| if payload = data[name] if payload.is_a?(Hash) || (payload.is_a?(Array) && payload.all? { |x| x.is_a?(Hash) }) # Assume nested attributes assignment. attributes_key = "#{name}_attributes" data[attributes_key] = data.delete(name) unless data[attributes_key] elsif id_field = RESTFramework::Utils.id_field_for(name, ref) # Assume id/ids assignment. data[id_field] = data.delete(name) unless data[id_field] end end end # ActiveStorage Integration: Translate base64 encoded attachments to upload objects. # # rubocop:disable Layout/LineLength # # Example base64 images (red, green, and blue squares): # data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mP8z8BQz0AEYBxVSF+FABJADveWkH6oAAAAAElFTkSuQmCC # data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNk+M9Qz0AEYBxVSF+FAAhKDveksOjmAAAAAElFTkSuQmCC # data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNkYPhfz0AEYBxVSF+FAP5FDvcfRYWgAAAAAElFTkSuQmCC # # rubocop:enable Layout/LineLength has_many_attached_scalar_data = {} if self.class.enable_active_storage self.class.model..keys.each do |k| if data[k].is_a?(Array) data[k] = data[k].map { |v| if v.is_a?(String) v = BASE64_TRANSLATE.call(k, v) # Remember scalars because Rails strong params will remove it. if v.is_a?(String) has_many_attached_scalar_data[k] ||= [] has_many_attached_scalar_data[k] << v end elsif v.is_a?(Hash) if v[:io].is_a?(String) v[:io] = StringIO.new(Base64.decode64(v[:io])) end end next v } elsif data[k].is_a?(Hash) if data[k][:io].is_a?(String) data[k][:io] = StringIO.new(Base64.decode64(data[k][:io])) end elsif data[k].is_a?(String) data[k] = BASE64_TRANSLATE.call(k, data[k]) end end end # Filter the request body with strong params. If `bulk` is true, then we apply allowed # parameters to the `_json` key of the request body. body_params = if allowed_params == true ActionController::Parameters.new(data).permit! elsif bulk_mode pk = bulk_mode == :update ? [ pk ] : [] ActionController::Parameters.new(data).permit({ _json: allowed_params + pk }) else ActionController::Parameters.new(data).permit(*allowed_params) end # ActiveStorage Integration: Workaround for Rails strong params not allowing you to permit an # array containing a mix of scalars and hashes. This is needed for `has_many_attached`, because # API consumers must be able to provide scalar `signed_id` values for existing attachments along # with hashes for new attachments. It's worth mentioning that base64 scalars are converted to # hashes that conform to the ActiveStorage API. has_many_attached_scalar_data.each do |k, v| body_params[k].unshift(*v) end # Filter read-only fields. body_params.delete_if do |f, _| cfg = self.class.field_configuration[f] cfg && cfg[:read_only] end body_params end |
#get_fields ⇒ Object
571 572 573 |
# File 'lib/rest_framework/controller.rb', line 571 def get_fields self.class.get_fields(input_fields: self.class.fields) end |
#get_index_records ⇒ Object
Get records with both filtering and pagination applied.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/rest_framework/controller/crud.rb', line 22 def get_index_records records = self.get_records # Handle pagination, if enabled. if paginator_class = self.class.paginator_class # Paginate if there is a `max_page_size`, or if there is no `page_size_query_param`, or if the # page size is not set to "0". max_page_size = self.class.max_page_size page_size_query_param = self.class.page_size_query_param if max_page_size || !page_size_query_param || params[page_size_query_param] != "0" paginator = paginator_class.new(data: records, controller: self) page = paginator.get_page serialized_page = self.serialize(page) return paginator.get_paginated_response(serialized_page) end end records end |
#get_record ⇒ Object
Get a single record by primary key or another column, if allowed.
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 |
# File 'lib/rest_framework/controller.rb', line 755 def get_record return @record if @record find_by_key = self.class.model.primary_key is_pk = true # Find by another column if it's permitted. if find_by_param = self.class.find_by_query_param.presence if find_by = params[find_by_param].presence find_by_fields = self.class.find_by_fields&.map(&:to_s) if !find_by_fields || find_by.in?(find_by_fields) is_pk = false unless find_by_key == find_by find_by_key = find_by end end end # Get the recordset, filtering if configured. collection = if self.class.filter_recordset_before_find self.get_records else self.get_recordset end # Return the record. Route key is always `:id` by Rails' convention. if is_pk @record = collection.find(request.path_parameters[:id]) else @record = collection.find_by!(find_by_key => request.path_parameters[:id]) end end |
#get_records ⇒ Object
Filter the recordset and return records this request has access to.
746 747 748 749 750 751 752 |
# File 'lib/rest_framework/controller.rb', line 746 def get_records data = self.get_recordset @records ||= self.class.filter_backends&.reduce(data) { |d, filter| filter.new(controller: self).filter_data(d) } || data end |
#get_recordset ⇒ Object
Get the set of records this controller has access to.
734 735 736 737 738 739 740 741 742 743 |
# File 'lib/rest_framework/controller.rb', line 734 def get_recordset return self.class.recordset if self.class.recordset # If there is a model, return that model's default scope (all records by default). if self.class.model return self.class.model.all end nil end |
#get_serializer_class ⇒ Object
458 459 460 |
# File 'lib/rest_framework/controller.rb', line 458 def get_serializer_class self.class.serializer_class || RESTFramework::NativeSerializer end |
#index ⇒ Object
17 18 19 |
# File 'lib/rest_framework/controller/crud.rb', line 17 def index render(api: self.get_index_records) end |
#openapi_document ⇒ Object
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/rest_framework/controller/openapi.rb', line 225 def openapi_document first, *rest = self.route_groups.to_a document = self.class.openapi_document(request, *first) if self.class.openapi_include_children rest.each do |route_group_name, routes| controller = "#{routes.first[:route].defaults[:controller]}_controller".camelize.constantize child_document = controller.openapi_document(request, route_group_name, routes) # Merge child paths and tags into the parent document. document[:paths].merge!(child_document[:paths]) document[:tags] += child_document[:tags] # If the child document has schemas, merge them into the parent document. if schemas = child_document.dig(:components, :schemas) # rubocop:disable Style/Next document[:components] ||= {} document[:components][:schemas] ||= {} document[:components][:schemas].merge!(schemas) end end end document end |
#options ⇒ Object
567 568 569 |
# File 'lib/rest_framework/controller.rb', line 567 def render(api: self.openapi_document) end |
#render_api(payload, **kwargs) ⇒ Object Also known as: api_response
Render a browsable API for ‘html` format, along with basic `json`/`xml` formats, and with support or passing custom `kwargs` to the underlying `render` calls.
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/rest_framework/controller.rb', line 493 def render_api(payload, **kwargs) html_kwargs = kwargs.delete(:html_kwargs) || {} json_kwargs = kwargs.delete(:json_kwargs) || {} xml_kwargs = kwargs.delete(:xml_kwargs) || {} # Raise helpful error if payload is nil. Usually this happens when a record is not found (e.g., # when passing something like `User.find_by(id: some_id)` to `render_api`). The caller should # actually be calling `find_by!` to raise ActiveRecord::RecordNotFound and allowing the REST # framework to catch this error and return an appropriate error response. if payload.nil? raise RESTFramework::NilPassedToRenderAPIError end # If `payload` is an `ActiveRecord::Relation` or `ActiveRecord::Base`, then serialize it. if payload.is_a?(ActiveRecord::Base) || payload.is_a?(ActiveRecord::Relation) payload = self.serialize(payload) end # Do not use any adapters by default, if configured. if self.class.disable_adapters_by_default && !kwargs.key?(:adapter) kwargs[:adapter] = nil end # Flag to track if we had to rescue unknown format. already_rescued_unknown_format = false begin respond_to do |format| if payload == "" format.json { head(kwargs[:status] || :no_content) } if self.class.serialize_to_json format.xml { head(kwargs[:status] || :no_content) } if self.class.serialize_to_xml else format.json { render(json: payload, **kwargs.merge(json_kwargs)) } if self.class.serialize_to_json format.xml { render(xml: payload, **kwargs.merge(xml_kwargs)) } if self.class.serialize_to_xml # TODO: possibly support more formats here if supported? end format.html { @payload = payload if payload == "" @json_payload = "" if self.class.serialize_to_json @xml_payload = "" if self.class.serialize_to_xml else @json_payload = payload.to_json if self.class.serialize_to_json @xml_payload = payload.to_xml if self.class.serialize_to_xml end @title ||= self.class.get_title @description ||= self.class.description self.route_groups begin render(**kwargs.merge(html_kwargs)) rescue ActionView::MissingTemplate # A view is not required, so just use `html: ""`. render(html: "", layout: true, **kwargs.merge(html_kwargs)) end } end rescue ActionController::UnknownFormat if !already_rescued_unknown_format && rescue_format = self.class.rescue_unknown_format_with request.format = rescue_format already_rescued_unknown_format = true retry else raise end end end |
#root ⇒ Object
Default action for API root.
113 114 115 |
# File 'lib/rest_framework/controller.rb', line 113 def root render(api: { message: "This is the API root." }) end |
#route_groups ⇒ Object
487 488 489 |
# File 'lib/rest_framework/controller.rb', line 487 def route_groups @route_groups ||= RESTFramework::Utils.get_routes(Rails.application.routes, request) end |
#rrf_error_handler(e) ⇒ Object
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/rest_framework/controller.rb', line 469 def rrf_error_handler(e) status = case e when ActiveRecord::RecordNotFound 404 else 400 end render( api: { message: e., errors: e.try(:record).try(:errors), exception: RESTFramework.config.show_backtrace ? e. : nil, }.compact, status: status, ) end |
#serialize(data, **kwargs) ⇒ Object
Serialize the given data using the ‘serializer_class`.
463 464 465 466 467 |
# File 'lib/rest_framework/controller.rb', line 463 def serialize(data, **kwargs) RESTFramework::Utils.wrap_ams(self.get_serializer_class).new( data, controller: self, **kwargs ).serialize end |
#show ⇒ Object
42 43 44 |
# File 'lib/rest_framework/controller/crud.rb', line 42 def show render(api: self.get_record) end |
#update ⇒ Object
46 47 48 |
# File 'lib/rest_framework/controller/crud.rb', line 46 def update render(api: self.update!) end |
#update! ⇒ Object
Perform the ‘update!` call and return the updated record.
51 52 53 54 55 |
# File 'lib/rest_framework/controller/crud.rb', line 51 def update! record = self.get_record record.update!(self.get_update_params) record end |
#update_all ⇒ Object
22 23 24 25 26 |
# File 'lib/rest_framework/controller/bulk.rb', line 22 def update_all records = self.update_all! serialized_records = self.bulk_serialize(records) render(api: serialized_records) end |
#update_all! ⇒ Object
Perform the ‘update` call and return the collection of (possibly) updated records.
29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/rest_framework/controller/bulk.rb', line 29 def update_all! pk = self.class.model.primary_key data = if params[:_json].is_a?(Array) self.get_create_params(bulk_mode: :update)[:_json].index_by { |r| r[pk] } else create_params = self.get_create_params { create_params[pk] => create_params } end # Perform bulk update in a transaction. ActiveRecord::Base.transaction { self.get_recordset.update(data.keys, data.values) } end |