# How to prevent user assign value to attribute in ActiveRecord

**URL:** <https://www.ruby-forum.com/t/how-to-prevent-user-assign-value-to-attribute-in-activerecord/163992>\
**Category:** Rails\
**Created:** [March 26, 2009, 6:17pm UTC](https://www.ruby-forum.com/t/how-to-prevent-user-assign-value-to-attribute-in-activerecord/163992 "2009-03-26T18:17:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![noelnoelu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/7ea924/32.png) [@noelnoelu](https://www.ruby-forum.com/u/noelnoelu)\
**Post date:** [March 26, 2009, 6:17pm UTC](https://www.ruby-forum.com/t/how-to-prevent-user-assign-value-to-attribute-in-activerecord/163992/1 "2009-03-26T18:17:36Z")

</div>

I have class bill like below

class Bill \< ActiveRecord::Base

#total = field in database

has\_many :items

after\_save :calculate\_total

def calculate\_total  
total = self.items.map{|item| item.price}.sum  
end

end

From the code above, the total will be auto calculated from on the  
price on each items in this bill. However, user can try to assign the  
value of this bill but when save the value with be replace with  
after\_save calculate\_total.

The question is

Do we have a way to prevent user to directly assign the total value  
but allow the calculate\_total to assign the value?

---

<div class="post-metadata">

**Author:** ![noelnoelu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/7ea924/32.png) [@noelnoelu](https://www.ruby-forum.com/u/noelnoelu)\
**Post date:** [March 26, 2009, 6:25pm UTC](https://www.ruby-forum.com/t/how-to-prevent-user-assign-value-to-attribute-in-activerecord/163992/2 "2009-03-26T18:25:50Z")

</div>

On 26 Mar., 18:16, noelnoelu [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> def calculate\_total  
> The question is
> 
> Do we have a way to prevent user to directly assign the total value  
> but allow the calculate\_total to assign the value?

Back in episode 26 of Railscasts, Ryan B. covered this excact  
problem with mass assignment. Enjoy the screencast:

> **[\#26 Hackers Love Mass Assignment - RailsCasts](http://railscasts.com/episodes/26-hackers-love-mass-assignment)**
>
> Short Ruby on Rails screencasts containing tips, tricks and tutorials. Great for both novice and experienced web developers.

–  
Best regards,  
David K.  
[http://twitter.com/rubyguy](http://twitter.com/rubyguy)
