State Model Design Model

I am having problems implementing statuses for the model. This is probably due to the wrong design.

There is a model that has a status. There can be several instances of the model and only a few predefined statuses (for example: created, updated, retrieved, etc.). For each individual state, there is a certain calculation logic for the model. For example. model.cost()calculated differently for each state.

I want ActiveRecord to automatically set the correct one model_status_idwhen saving the model. I think in an ideal situation I could do something like this:

model.status = StatusModel.retrieved

and

case status
  when renewed
    # ...
  when retrieved
    # ..
end

I think I need to save the status in the model line in the database, this is what I have now:

ModelStatus < ActiveRecord::Base
  has_many :models
Model < ActiveRecord::Base
  belongs_to :model_status

. - ?

+3
3

? , :

class Model < ActiveRecord::Base

  STAT_CREATED   = 1 
  STAT_RENEWED   = 2
  STAT_RETRIEVED = 4

  validates_inclusion_of :status,
                         :in => [1, 2, 4]


  def created?
    status & STAT_CREATED
  end

  def renewed?
    status & STAT_RENEWED
  end

  def retrieved?
    status & STAT_RETRIEVED
  end

end

, (, @model.created?), :

case @model.status
when Model::STAT_CREATED
...
when Model::STAT_RENEWED
...
+1

, , .

Ruby. ruby-toolbox

. , . DSL .

model.retrieve!

, , , .

+2
+1

Source: https://habr.com/ru/post/1715976/


All Articles