diff --git a/app/controllers/admin/poll/questions/answers_controller.rb b/app/controllers/admin/poll/questions/answers_controller.rb index 4e420575f..bef176a22 100644 --- a/app/controllers/admin/poll/questions/answers_controller.rb +++ b/app/controllers/admin/poll/questions/answers_controller.rb @@ -9,7 +9,6 @@ class Admin::Poll::Questions::AnswersController < Admin::Poll::BaseController def create @answer = ::Poll::Question::Answer.new(answer_params) - @answer.set_order if @answer.save redirect_to admin_question_path(@answer.question), diff --git a/app/models/poll/question/answer.rb b/app/models/poll/question/answer.rb index a7aa3339a..7514b85a4 100644 --- a/app/models/poll/question/answer.rb +++ b/app/models/poll/question/answer.rb @@ -10,6 +10,9 @@ class Poll::Question::Answer < ActiveRecord::Base has_many :videos, class_name: 'Poll::Question::Answer::Video' validates :title, presence: true + validates :given_order, presence: true, uniqueness: { scope: :question_id } + + before_validation :set_order, on: :create def description super.try :html_safe @@ -17,15 +20,16 @@ class Poll::Question::Answer < ActiveRecord::Base def self.order_answers(ordered_array) ordered_array.each_with_index do |answer_id, order| - answer = find(answer_id) - answer.update_attribute(:given_order, (order + 1)) - answer.save + find(answer_id).update_attribute(:given_order, (order + 1)) end end def set_order - last_position = Poll::Question::Answer.where(question_id: question_id).maximum("given_order") || 0 - next_position = last_position + 1 - update_attribute(:given_order, next_position) + next_position = self.class.last_position(question_id) + 1 + self.given_order = next_position + end + + def self.last_position(question_id) + where(question_id: question_id).maximum("given_order") || 0 end end diff --git a/spec/factories.rb b/spec/factories.rb index a28471efc..69aa92c62 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -503,8 +503,8 @@ FactoryGirl.define do factory :poll_question_answer, class: 'Poll::Question::Answer' do association :question, factory: :poll_question - sequence(:title) { |n| "Question title #{n}" } - sequence(:description) { |n| "Question description #{n}" } + sequence(:title) { |n| "Answer title #{n}" } + sequence(:description) { |n| "Answer description #{n}" } end factory :poll_booth, class: 'Poll::Booth' do