0

in this screencast Ryan Bates showed how to implement reputation system from scratch. But is there any way to give the current_user only 1 vote, and check whether user has already voted for application, and if yes, restrict the possibility of voting?

I think something like this in user.rb should work, but I don't know ho to exactly write it

   def has_one_vote
      Restrict amount of user votes to 1
   end

Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Ilya Cherevkov
  • 1,743
  • 2
  • 17
  • 47
  • There's not really enough information here to go on. What are the relationships between your models? – Jeremy Rodi Sep 04 '12 at 13:29
  • User has_many applications and application_votes. Application_votes belongs_to user and applications. Applications belongs_to user and has_many application_votes. Actually it is the same as in the cast, application instead of haiku Ryan used – Ilya Cherevkov Sep 04 '12 at 13:32
  • here is this from-scratch solution https://github.com/railscasts/364-active-record-reputation-system/tree/master/youhaiku-from-scratch – Ilya Cherevkov Sep 04 '12 at 13:34
  • Are you going to pass an argument to `has_one_vote` containing the Application instance you're checking for a vote? – Jeremy Rodi Sep 04 '12 at 13:34
  • I just want to check whether current_user has the ability to vote for application. If he does not exhausted the limit of votes (which is just 1) , than he can vote, otherwise he cannot – Ilya Cherevkov Sep 04 '12 at 13:41
  • @IlyaCherevkov Please don't post this information in comments. Edit it into your question with the **edit** link below your post – user229044 Sep 04 '12 at 13:47

1 Answers1

1

I'm assuming you have Users, Votes, and Posts, and that users vote on posts.

You should add a uniqueness validator to the Vote class on the user_id attribute, scoped to the post_id. This limits the number of votes a user can have on a given post to one:

class Vote
  belongs_to :user
  belongs_to :post

  validates :user_id, uniquness: { scope: :post_id }
end

To limit the total number of votes a user can ever create, either remove the scope from the uniqueness validator, or (more correctly) move the foreign key into the users table.

That is, either this:

class Vote
  belongs_to :user
  belongs_to :post
  validates :user_id, uniquness: true
end

or this:

class User
  belongs_to :vote
end
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Thanks, but this restricts number of votes to 1 for one particular post, and I want to restrict it for all posts, e.g. If user voted for 1 post, he cannot give another vote for another post – Ilya Cherevkov Sep 04 '12 at 13:49
  • Then remove the `scope`, and the user will only be able to ever create one Vote. See my updated answer. – user229044 Sep 04 '12 at 13:55