不允许用户投票支持自己的帖子

时间:2012-07-16 19:03:55

标签: ruby-on-rails ruby

我有三种模式用户发布投票

我需要不允许用户投票支持自己的帖子。 我如何在我的模型中进行此操作并在Rspec中进行测试?

发布模型:

class Post < ActiveRecord::Base
  attr_accessible :title, :main_text, :video, :photo, :tag

  validates :title,     presence: true, length:  {minimum: 1, maximum: 200}
  validates :main_text, presence: true, length:  {minimum: 1}

  belongs_to :user
  has_many   :votes

end

用户模型:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :bio

  has_many :posts
  has_many :votes

  validates :name,  presence: true, length: {minimum: 1, maximum: 120}
  validates :email, presence: true, length: {minimum: 5, maximum: 250}, uniqueness: true, 
                    format: {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}


end

投票模型:

class Vote < ActiveRecord::Base

  attr_accessible :user_id, :post_id, :units

  belongs_to :user
  belongs_to :post

  validates :post_id, uniqueness: {scope: :user_id}  #does not allow user to vote for the same post twice


end

我对投票的规格测试:

require 'spec_helper'

describe Vote do

  it "does not allow user to vote for the same post twice" do 
    user = User.create(name: "Nik", email: "nik@google.com" )
    post = Post.create(title: "New Post", main_text: "Many, many, many...")
    vote1 = Vote.create(user_id: user.id, post_id: post.id)  
    vote1.errors.should be_empty    
    vote2 = Vote.create(user_id: user.id, post_id: post.id)        
    vote2.errors.should_not be_empty      
  end 

  it "does not allow user to vote for his own post" do
    user = User.create(name:"Nik", email:"a@a.ru")
    post = Post.create(user_id: user.id, title: "New Post", main_text: "Many, many, many...")
    vote1 = Vote.create(user_id: user.id, post_id: post.id)
    vote1.errors.should_not be_empty
  end

end

2 个答案:

答案 0 :(得分:2)

我没有测试过以下代码,所以它无法工作甚至杀死你的猫,但尝试使用自定义验证,如果投票的用户与帖子的用户相同,则添加错误。

请注意,如果用户或帖子由于obvius原因而为零,则返回。

# In your vote model
validate :users_cant_vote_their_posts

def users_cant_vote_their_posts
  return if user.nil? or post.nil?
  if user_id == post.user_id
    errors[:base] = "A user can't vote their posts"
  end
end

编辑:这是一个可能的测试,这里我使用FactoryGirl来生成投票。再次对此代码进行测试(对不起双关语)

describe Vote do
  subject { vote }

  let!(:vote) { FactoryGirl.build(:vote) }

  it 'from factory should be valid' do
    should be_valid
  end

  context 'when user try to double vote' do
    before do
      # Create another vote from user to post
      FactoryGirl.create(:vote, :user => vote.user, :post => vote.post)
    end

    it { should_not be_valid }
  end

  context 'when user try to vote his posts' do
    before do
      # Set the user whom voted to the post's owner
      vote.user = vote.post.user
    end

    it { should_not be_valid }
  end

end

答案 1 :(得分:0)

我不知道ruby,但您应该检查登录的用户是否与发布帖子的用户匹配。如果确实如此,则拒绝投票请求。

很抱歉,如果这没有帮助:)