Validation question

I have a courses model that has two fields:

courses(title, members_count)

Is it possible to have a validation that only lets the user update the
title if members_count == 0?

def validate
errors.add(:title, “cannot be changed once users have signed up”) if
members_count > 0 and title_changed
end

But I’m not sure how to check that the title has changed - any help is
appreciated. Thanks!

I’ve never liked the solutions I’ve come up with… but from a
practical perspective you might simply disable the text_field if
member_count>0.

Create a hidden field old_title. You’ll need to add an attr_accessor,
but then you should be able to check if old_title == title. But I
liked the other suggestion better… why have the text field if it
can’t be changed? Perhaps you should render a partial that only shows
the enabled text field if member_count<0

-Ryan

I thought about something like that, but I think it would fairly easy
to bypass - all the user would need to do is change the form and
submit it to change the title regardless of members_count. Any other
ideas? My guess is that this is a fairly common type of validation
people need to perform…

I got something that works by saving the previous title from the
controller:

def update
@course = Course.find params[:id]
@course.save_previous_title
@course.attributes = params[:course]
@course.save!
flash[:notice] = “Class #{@course.title} updated”
redirect_to_course
rescue ActiveRecord::RecordInvalid
render :action => :new
end

and in models/course.rb

attr_accessor :previous_title
def save_previous_title
self.previous_title = title
end

def validate
errors.add(:title, “cannot be changed once users have signed up”)
if members_count > 0 and title != previous_title
end

It doesn’t feel very clean though - anyone know if I can set a
callback to save_previous_title in the model before it updates itself
so I don’t have to call it explicitly from the controller or if there
is a better way to go about this?