From 00564fc501e4eb6d03e74b975a12ebf0ae6171fe Mon Sep 17 00:00:00 2001 From: lukaszreszke Date: Mon, 23 Sep 2024 19:01:39 +0200 Subject: [PATCH] Breaking the law breaking the law --- .../app/controllers/products_controller.rb | 17 +++---------- rails_application/app/models/product.rb | 24 +++++++++++++++++++ .../app/views/products/new.html.erb | 6 +++++ 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/rails_application/app/controllers/products_controller.rb b/rails_application/app/controllers/products_controller.rb index 99974eb8..96c1c6e1 100644 --- a/rails_application/app/controllers/products_controller.rb +++ b/rails_application/app/controllers/products_controller.rb @@ -25,20 +25,9 @@ def create def update @product = Product.find(params[:id]) - if params["future_price"].present? - @product.future_price = params["future_price"]["price"] - @product.future_price_start_time = params["future_price"]["start_time"] - @product.save! - else - ApplicationRecord.transaction do - @product_with_new_price = @product.dup - @product_with_new_price.price = product_params[:price] - @product_with_new_price.latest = true - @product.latest = false - @product_with_new_price.save! - @product.save! - end - end + @product.change_name(params[:product][:name]) + @product.change_price!(product_params) + redirect_to products_path, notice: "Product was successfully updated" end diff --git a/rails_application/app/models/product.rb b/rails_application/app/models/product.rb index 0399700e..f18e1cb7 100644 --- a/rails_application/app/models/product.rb +++ b/rails_application/app/models/product.rb @@ -19,4 +19,28 @@ def validate_vat_rate errors.add(:vat_rate, "is not a number") end end + + def change_name(new_name) + return if new_name == self.name || new_name.blank? + self.name = new_name + self.save! + end + + def change_price!(params) + if params["future_price"].present? + + self.future_price = params["future_price"]["price"] + self.future_price_start_time = params["future_price"]["start_time"] + self.save! + else + ApplicationRecord.transaction do + product_with_new_price = self.dup + product_with_new_price.price = params[:price] + product_with_new_price.latest = true + self.latest = false + product_with_new_price.save! + self.save! + end + end + end end diff --git a/rails_application/app/views/products/new.html.erb b/rails_application/app/views/products/new.html.erb index d1d79e80..7d2a99dd 100644 --- a/rails_application/app/views/products/new.html.erb +++ b/rails_application/app/views/products/new.html.erb @@ -20,6 +20,12 @@ <%= form.text_field :name, required: true, class: "mt-1 focus:ring-blue-500 focus:border-blue-500 block shadow-sm sm:text-sm border-gray-300 rounded-md", data: { turbo_permanent: true } %> +
+ + <%= form.text_field :sku, required: true, class: "mt-1 focus:ring-blue-500 focus:border-blue-500 block shadow-sm sm:text-sm border-gray-300 rounded-md", data: { turbo_permanent: true } %> +