Вопрос

I am working on a multiple choice question and answer application using Ruby on Rails and I have the following model.

class User < ActiveRecord::Base
  has_many :questions
end  

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
  has_many :votes
end

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :answer
end

My problem is a user can choose all the answers.

How can I fix it so that it updates to the new answer?

For example, a has 5 votes and b 3 votes.

User clicks on a and a increments to 6 votes, same user comes back and clicks on b, a decrements back to 5 votes and b increments to 4 votes.

My first guess is that I need to add another model for example, user_choice with user_id and vote_id to track the previous answer.

Это было полезно?

Решение

You have your answer within the models. Just add a point system to the question model.

Under the question model,

def points
  self.answers.count
end

Or, if answers have different values attached to them, make points an attribute of the answer instances.

def points
  self.answers.pluck(:points).inject(:+)
end

This will sum up all the points from an answer belonging to a question, which allows you to order the questions by point count.

However, I am assuming you will need a Choice model for a question, unless that is in fact what the votes are for.

question has_many choices

choices belong_to question, etc.

I'm not sure what you mean when you say:

How can I fix it so that it updates to the new answer?

EDIT

Er, okay so you just need exactly what I mentioned earlier. A vote is really just the number of times an answer has been chosen.

If your problem is that users can choose more than 1 answer, it is likely that you should implement view based validations via javascript, or better yet, just disable their ability to select multiple choices, which if you were using a select tag, is actually the default. You must've added

multiple: true

in the select tag options for the user to select multiple entries.

On the backend, you can do this:

class Choice < ActiveRecord::Base
validates_uniqueness_of :user_id, scope: [:question_id, :answer_id]
end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top