Avishai
Avishai

Reputation: 4732

Accept Rails model attribute only if it was previously blank

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?

Upvotes: 0

Views: 340

Answers (2)

rik.vanmechelen
rik.vanmechelen

Reputation: 1914

The easiest way, i think, is by checking for it in the form itself. Just say add :disabled => true to the input field if the person cannot edit it.

<% if @my_object.name %>
   <%= f.text_field :name, :disabled => true %>
<% else %>
   <%= f.text_field :name, :disabled => true %>
<% end %>    

(i think there is a prettier way to write this code)

But by using this the user has a visual feed back that he can't do something, it is always better to not allor something than to give an error message

Upvotes: 0

Gareth
Gareth

Reputation: 138042

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

Upvotes: 2

Related Questions