Skip to main content

Scoping for nested atrributes rails 4 [Resolved]

I'm fairly new to Rails. I'm trying to create a voting system where people can vote one answer in a question.


has_many :choices, dependent: :destroy

accepts_nested_attributes_for :choices, reject_if: proc { |attributes| attributes['option'].blank?}, allow_destroy: true

validates_presence_of :title, :user_id


belongs_to :question
has_many :votes, dependent: :destroy


belongs_to :voter, class_name: 'User'
belongs_to :choice

validates_presence_of :voter_id, :choice_id
validates_uniqueness_of :voter, scope: :choice

Now the scope I have in the "Vote" model only check uniqueness of a choice (I can only vote for that choice once) but I can still vote for other choices in the same question. I would like to be able to vote in a question once. So the question and the choice is unique. I think I need to create a custom scope, but I don't know how.

Question Credit: Pier Yos
Question Reference
Asked June 13, 2016
Posted Under: Programming
1 Answers

Your Answer