noelnoelu
2009-Mar-26 17:16 UTC
How to prevent user assign value to attribute in ActiveRecord
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?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---
rubyguy-DaQTI0RpDDMAvxtiuMwx3w@public.gmane.org
2009-Mar-26 17:25 UTC
Re: How to prevent user assign value to attribute in ActiveRecord
On 26 Mar., 18:16, noelnoelu <noelno...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> 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?Back in episode 26 of Railscasts, Ryan Bates covered this excact problem with mass assignment. Enjoy the screencast: http://railscasts.com/episodes/26-hackers-love-mass-assignment -- Best regards, David Knorr http://twitter.com/rubyguy --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---