Srikan
Srikan

Reputation: 2241

Active record update attributes without attr_accessible

I have a model Article. Once it is created we send a activation code to the user with a token. this activation code is on purpose black listed , so it is not added to the attr_accesible list.

once the user comes back to activate the code

articleitem = Article.find_by_activation_code(params[:code])
articleitem.activation_code = ""

Now how do we update the record. I don't want to use the save since it activates the before_save methods

I have tried all the below in the controller.

articleItem.update(activation_code: "")
update method is private

articleItem.update_attributes(activation_code: "")
WARNING: Can't mass-assign protected attributes: activation_code

What are the other alternatives to update the record

Upvotes: 0

Views: 266

Answers (1)

Pramod Solanky
Pramod Solanky

Reputation: 1690

An alternative approach would be to set a virtual attribute (Untested code)

in model

attr_accessor :execute_before_save
before_save :some_method

def some_method
  # Check is execute_before_save is set, if not let the method execute no matter what
  if execute_before_save || true
     # your code follows
  end
end

in your controller

articleitem = Article.find_by_activation_code(params[:code])
articleItem.execute_before_save = false
articleitem.activation_code = ""
articleitem.save

That way you control your before_save callback but it requires you to set the virtual attribute which is overhead.

Let me know if it helps.

Upvotes: 1

Related Questions