5

Accept the Rails model attribute only if it was already empty

 2 years ago
source link: https://www.codesd.com/item/accept-the-rails-model-attribute-only-if-it-was-already-empty.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Accept the Rails model attribute only if it was already empty

advertisements

I have a Rails model (persisted with Mongoid) that can be collaboratively edited by any registered user. However, I want to allow editing any particular attribute only if it was previously blank or nil.

For example, say someone created an object, and set its title attribute to "Test Product". Then another user comes along and wants to add a value for price, which until now has been nil.

What's the best way to do this, while locking an attribute that has previously been entered?


Look into the ActiveRecord::Dirty module for some nice utility methods you can use to do something like this:

NON_UPDATABLE_ATTRIBUTES = [:name, :title, :price]
before_validation :check_for_previously_set_attributes

private
def check_for_previously_set_attributes
  NON_UPDATABLE_ATTRIBUTES.each do |att|
    att = att.to_s
    # changes[att] will be an array of [prev_value, new_value] if the attribute has been changed
    errors.add(att, "cannot be updated because it has previously been set") if changes[att] && changes[att].first.present?
  end
end


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK