From 52cd3716c15cd5360f4f8a16ffaf2ba38ecb1c78 Mon Sep 17 00:00:00 2001 From: Petko Bordjukov Date: Wed, 5 Oct 2016 17:56:24 +0300 Subject: [PATCH] Store the selected talks as associated records --- app/assets/javascripts/halfnarp.js | 4 +++- .../talk_preferences_controller.rb | 23 +++++++++++-------- app/models/talk_preference.rb | 4 ++-- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/app/assets/javascripts/halfnarp.js b/app/assets/javascripts/halfnarp.js index 84f4eae..435c018 100644 --- a/app/assets/javascripts/halfnarp.js +++ b/app/assets/javascripts/halfnarp.js @@ -41,7 +41,9 @@ } /* Convert preferences to JSON and post them to backend */ - var request = {talk_preference: {'talks': ids}}; + var request = {talk_preference: {'selected_talks_attributes': ids.map(function(talk_id) { + return {"talk_id": talk_id}; + })}}; if( !myapi || !myapi.length ) { /* If we do not have resource URL, post data and get resource */ $.post( halfnarpAPI, request, function( data ) { diff --git a/app/controllers/talk_preferences_controller.rb b/app/controllers/talk_preferences_controller.rb index f5d831b..61fafe2 100644 --- a/app/controllers/talk_preferences_controller.rb +++ b/app/controllers/talk_preferences_controller.rb @@ -26,20 +26,25 @@ class TalkPreferencesController < ApplicationController def update @talk_preference = TalkPreference.find params[:id] - if @talk_preference.update talk_preference_params - render json: { - update_url: talk_preference_url(@talk_preference), - hashed_uid: @talk_preference.hashed_unique_id, - uid: @talk_preference.id - } - else - render status: :unprocessable_entity + @talk_preference.transaction do + @talk_preference.selected_talks.destroy_all + + if @talk_preference.update talk_preference_params + render json: { + update_url: talk_preference_url(@talk_preference), + hashed_uid: @talk_preference.hashed_unique_id, + uid: @talk_preference.id + } + else + head :unprocessable_entity + raise ActiveRecord::Rollback + end end end private def talk_preference_params - params.require(:talk_preference).permit(talks: []) + params.require(:talk_preference).permit(selected_talks_attributes: [:talk_id]) end end diff --git a/app/models/talk_preference.rb b/app/models/talk_preference.rb index fc5a2d3..97a8b18 100644 --- a/app/models/talk_preference.rb +++ b/app/models/talk_preference.rb @@ -1,7 +1,7 @@ class TalkPreference < ActiveRecord::Base - has_many :selected_talks - self.primary_key = :unique_id + has_many :selected_talks + accepts_nested_attributes_for :selected_talks before_create :assign_new_unique_id