开发者

Different components, different quantities, different rules... too many!

开发者 https://www.devze.com 2023-02-06 03:09 出处:网络
Suppose I have a product, which consists of two components, X qty of Component A, and Y qty of component B.

Suppose I have a product, which consists of two components, X qty of Component A, and Y qty of component B.

When I select it in the form or the user to edit it, I bring the default quantities, but I need to allow the used to edit X to any number they like, but if they choose to do so, I need to update my Y qty, to always be double of whatever they chose as the new X.

This is how the business rule looks for this product. There are many other products and each has its own number of components and interlinked quantities. What is the best way to manage this as the 开发者_JAVA百科rules change quite often (and there's a lot of them)?

Someone suggested using JSON to validate at the server-side, but I'm quite new to this and I need some simple example at least to get me going on how this would be handled by the server and how it would look like.

I appreciate any advice!


I don't think you need any server validations until the user actually presses Save or Update or whatever. When rendering the form for the user, include some simple js functions that handles the rules.

So if the user changes the value for X qty then set the Y qty to double that through onChange or onBlur events, all client-side. Then when user posts the data to the server, check if the quantities are valid by some custom validate callback in your model and raise an error if it is not.

Here is just an example of a model:

class Product < ActiveRecord::Base
  X_Y_RATIO = 2

  validate :x_y_ratio

private
  def x_y_ratio
    (self.y_qty / self.x_qty) == X_Y_RATIO
  end
end

So if the x_y_ratio method returns false then the product will not be saved.

0

精彩评论

暂无评论...
验证码 换一张
取 消