Controllers, Models, and Validations

Hello,

After listening to DHH’s 2006 RailsConf keynote, I decided to take a
leap on my current application and do a little more re-organizing to
make it more CRUD-based. As such, I ended up changing some things
around to get this (simplified):

User has_many :enrollments, :conditions => ‘status > 0’
User has_many :schools, :through => :enrollments
User has_many :memberships, :conditions => ‘status > 0’
User has_many :groups, :through => :memberships

If a user leaves a school or a group, the status is just reset to 0. I
am having a bit of a dilemma, however. When a user joins a group
(creates an enrollment), there are several things that need to be
checked:

  1. We need a valid user id
  2. We need a valid group id
  3. The group’s school_id must be the same as the user’s currently
    active enrollment school_id (there is only one enrollment active at a
    time)
  4. You can’t join a group you already belong to (in other words,
    create duplicate memberships)

Logically, this should go in the Membership model, right? I had put it
in the controller, but then I realized that I was putting too much of
the data-handling functions in the controller. The problem becomes
that: How do I display errors if it is validated in the Membership
model.

Consider the user’s school_id in their currently active enrollment (in
other words @user.schools[0].id because there is only one element in
that array at a time) is different than the school_id in the Group
model. In a controller I would do:

unless @user.schools[0].id [email protected]_id
flash[:notice] = ‘Sorry, you can’t join a group when you don’t
belong to the same school!’
return redirect_to(home_url)
end

In a model, however, the only thing I can think of is putting this
type of validation in the validate() method and then calling
errors.add(). However, the first parameter has to be the attribute in
the Enrollment object that isn’t valid! Obviously the user’s school_id
doesn’t belong the the Enrollment object. And beyond that, where would
I call error_messages_for()? Really, it isn’t a traditional form. It
wouldn’t make sense to have the user enter their user_id and their
group_id – the application handles this, they just click the “Join
group” button.

Am I looking at this wrong? I would really appreciate some help!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs