Skip to content
Snippets Groups Projects
Commit 47028120 authored by Marcela Ribeiro de Oliveira's avatar Marcela Ribeiro de Oliveira
Browse files

add unique index to collections

parent e6f79e0a
No related branches found
No related tags found
No related merge requests found
......@@ -7,7 +7,7 @@ class V1::CollectionsController < ApplicationController
include ::Paginator
before_action :set_collection, only: [:show, :update, :destroy, :add_object]
before_action :set_collection, only: [:show, :update, :destroy, :add_object, :set_collection_items]
before_action :authenticate_user!, only: [:create, :update, :destroy]
# GET /v1/collections
......@@ -27,6 +27,7 @@ class V1::CollectionsController < ApplicationController
# POST /v1/collection.json
def create
collection = Collection.new(collection_params)
set_collection_items
if collection.save
render json: collection, status: :created
......@@ -38,6 +39,9 @@ class V1::CollectionsController < ApplicationController
# PUT/PATCH /v1/users/1
# PUT/PATCH /v1/users/1.json
def update
set_collection_items
if @collection.update(collection_params)
render json: @collection, status: :ok
else
......@@ -55,19 +59,7 @@ class V1::CollectionsController < ApplicationController
# POST /v1/collections/!/items
def add_object
render nothing: true, status: :unprocessable_entity if params.nil?
items = collection_params[:items]
items.each do |item|
order = item[:order]
item = item[:type].constantize.find(item[:id])
collection_item = { collection: @collection, collectionable: item, order: order }
collection_item = CollectionItem.new(collection_item)
collection_item.save
end
set_collection_items
render json: @collection, status: :ok
end
......@@ -85,6 +77,14 @@ class V1::CollectionsController < ApplicationController
@collection ||= Collection.find(params[:id])
end
def set_collection_items
items = collection_params[:items]
collection_items = items.map{ |item| CollectionItem.new(collection: @collection,
collectionable: item[:type].constantize.find(item[:id]),
order: item[:order])}
CollectionItem.import collection_items, on_duplicate_key_update: {conflict_target: [:collection_id, :collectionable_id, :collectionable_type]}
end
# Never trust parameters from the scary internet, only allow the white list through.
def collection_params
params.require(:collection).permit(:name, :description, :owner_id, :owner_type, :privacy, tags: [], items: [:type, :id])
......
class AddIndexToCollection < ActiveRecord::Migration[5.0]
def change
add_index :collection_items, [:collection_id,:collectionable_id, :collectionable_type], unique: true, name: 'collection_item_and_collectionable'
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment