CR7
CR7

Reputation: 710

Need to update parameters in model

I have two columns code1 and code2 in users model. I am trying to merge the values of the columns as code. I have written a migration file for that and I have removed code1 and code2. To work the old apps I need to accept code1 and code2 and combine it to get code. So I have permitted code1 and code2. But when I use old app I gets this error

unknown attribute 'code1' for User

In my controller I have wrote the following code

if user_params[:code1].present?
  user_params[:code] = user_params[:code1] + user_params[:code2]
  user_params.delete(:code1)
  user_params.delete(:code2)
end

But it is not working as expected. How can I support code1 in the old app.

Upvotes: 0

Views: 44

Answers (1)

Ankur Pohekar
Ankur Pohekar

Reputation: 139

I am not sure but try adding attr_accessor :code1, :code2 in User Model

once you define attr_accessor in User model and permitted it on Controller, you can write callback in User model and write self.code = self.code1 + self.code2

class User < ApplicationRecord
  attr_accessor :code1, :code2

  before_validation :demo_callback

  def demo_callback
    self.code = self.code1 + self.code2
  end

end

Upvotes: 1

Related Questions