I have fairly simple problem but I can not think of the simple solution. I have 3 models.
class User < ActiveRecord::Base
has_many :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :school
end
class School < ActiveRecord::Base
has_many :memberships
end
A User can create a membership for school(s). “membernumber” is given by school. So far so good.
Except one use case, where a membership record gets created by school without user_id value in memberships table.
In this case a record gets created with “membernumber”, “school_id” and empty “user_id” field.
What I want to do is, when a user tries to create his membership (using his “membernumber”) with a school, First I want to see if “user_id”, “membernumber”. school_id combination is unique if found (I used validates_uniqueness_of….).
If record not found than check a record/association with “membernumber” and school exists and it’s user_id field is empty. If that is the case then don’t create a new membership but just update it’s user_id field (with current_user.id) and return with a msg that a creation of new association is successful (as if its a new membership record).
How do I do this? Do I need to use any callbacks? How do I use callbacks in this case?
Any help is appreciated.
Thanks,
Atarangp
This is how I solved it.
In model membership, added a method membership_exists and called it from membership’s create
action.
And in Membership controller (in create action)
This works. But is it a good way to do it?
Thanks,
Atarangp.