attr_accessor
You'll need to use virtual attributes in your model:
#app/models/model.rb
Class Model < ActiveRecord::Base
attr_accessor :number_of_people, :cost
end
The way rails works is to process data based on the attached attributes
of a model. Since a model is just a class
, it means you can add extra attributes over the ones which will be defined in your database.
To do this, you'll have to use the attr_accessor
method to create a setter
& getter
for the attributes you wish to use. This acts in exactly the same way as if the attributes are defined in the database, except they won't be able to be saved
--
Controller
You should also ensure you remember to pass these parameters through your strong_params
method:
#app/controllers/model_controller.rb
Class ModelController < ActiveRecord::Base
...
def model_params
params.require(:model).permit(:your, :params, :including, :your, :virtual, :attrs)
end
end
--
Callback
How can I get those two values from the field, and then manipulate
them to produce my final value?
Apply the model data as above, and then I would set a before_create
callback like so:
#app/models/model.rb
Class Model < ActiveRecord::Base
...
before_create :set_values
private
def set_values
# ... set values here
end
end