Forum: Ruby on Rails How to prevent user assign value to attribute in ActiveRecord

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ba40fb9469683d3a161fb5e8ae370a6f?d=identicon&s=25 noelnoelu (Guest)
on 2009-03-26 18:17
(Received via mailing list)
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?
36ed63ef68c172f148c491418395d0b5?d=identicon&s=25 rubyguy@ymail.com (Guest)
on 2009-03-26 18:25
(Received via mailing list)
On 26 Mar., 18:16, noelnoelu <noelno...@gmail.com> 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 Bates covered this excact
problem with mass assignment. Enjoy the screencast:
http://railscasts.com/episodes/26-hackers-love-mas...

--
Best regards,
David Knorr
http://twitter.com/rubyguy
This topic is locked and can not be replied to.