使用IP地址

时间:2015-06-20 03:22:59

标签: ruby-on-rails voting voting-system

我希望允许用户在未注册的情况下对帖子进行投票,并将投票改为与其IP地址绑定。我试过跟this post,但我还需要进一步澄清。这是我从posts_controller获取的错误

  对于#

未定义的方法`find_or_create_by_ip'

到目前为止,这是我的代码:

posts_controller:

def upvote 
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    upvote = session.find_or_create_by_ip(session[:voting_id])
    @post.upvote
    redirect_to :back
  end

  def downvote  
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    downvote = session.find_or_create_by_ip(session[:voting_id])
    @post.downvote
    redirect_to :back
  end 

会话模型:

 class session < ActiveRecord::Base
    acts_as_voter
    request.remote_ip
end

routes.rb:

Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/about'
  resources :posts do
    member do 
      put "like" , to: "posts#upvote"
      put "dislike" , to: "posts#downvote"
    end
  end

other post有人说在会话表中添加 ip 列。这到底是什么意思呢?我还看到了我需要创建数据库表的地方。我呢?我该怎么做?很抱歉不得不发布这个,把我很新的,所以如果它对我来说更好的拼写会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您使用的是Rails 4+动态查找程序已deprecated并已提取到gem。该标准现在为find_or_create_byfind_or_initialize_by

def upvote 
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    upvote = Session.find_or_create_by(ip: session[:voting_id])
    @post.upvote
    redirect_to :back
end

def downvote  
  @post = Post.find (params[:id])
  session[:voting_id] = request.remote_ip
  downvote = Session.find_or_create_by(ip: session[:voting_id])
  @post.downvote
  redirect_to :back
end 

class Session < ActiveRecord::Base
  acts_as_voter
  request.remote_ip
end