views:

139

answers:

6

I am developing an application based on questions and answers, and I would like to prevent a registered user from posting multiple answers to the same question.

How can I do that? And where is the best place to put this code (i.e. controller, model)?

+5  A: 

You would need two checks, one when the questions loads to see if there is an answer by that user. If so, do not present him with the answer form.

And two, when a question is submitted, to check if there is already an answer by that user, if so, do not submit it.

Ólafur Waage
+1  A: 

Get the user id, get the question id. Check if there is an answer from the users id that corresponds to the question id. If it exists, say NO! If it does not exist then proceed with posting the answer...

Peter D
I know, right???
GreenieMeanie
+1  A: 

You want a validates_uniqueness_of validation in your model to enfore the rule - http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002110

I'd also agree with Ólafur you shouldn't give the user the button to add an answer if they have already added one.

RichH
+1  A: 

You have a question_id and a user_id, so what's the problem?

GreenieMeanie
A: 

You have a question_id and a user_id, so what's the problem?

GreenieMeanie
A: 

I finally wrote this code:


# Reply model
validates_uniqueness_of :user_id, :scope => :question_id

# Helper method
def user_has_replied(user, question)
  Reply.find( :first, :conditions => {:user_id => user.id, :question_id => question.id} )
end
collimarco