0

I want to collect a certain field from the User, but I first manipulate it before putting it in the database. I have begun to use strong paramaters and I'm confused on how to do this. I keep getting the error unpermitted parameters: number_of_people, cost.

Here is an example of what I am looking to do: If I don't want to collect the cost or number of people at an event, but only want to know the cost per person at an event, I would divide cost by number of people and then store that number in the database.

How can I get those two values from the field, and then manipulate them to produce my final value?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
David Mckee
  • 1,100
  • 3
  • 19
  • 35

1 Answers1

2

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
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147