ruby on rails - Save new user via IP alone (anonymous, like Yik Yak) -


i'm having trouble creating users via ip. no logins, no signups, yik yak. i'm able create users in terminal, can't seem translate code.

in terminal can create users doing this:

irb(main):001:0> user=user.new => #<user id: nil, current_ip: nil, created_at: nil, updated_at: nil> irb(main):002:0> user.current_ip="159.5.159.11" => "159.5.159.11" irb(main):003:0> user.save 

here's have @ point. can't ip save new user when run in rails server. missing here?

routes.rb

rails.application.routes.draw resources :users  root 'users#create' 

users_controller

class userscontroller < applicationcontroller before_action :set_user, only: [:show, :edit, :update, :destroy] cattr_accessor :current_ip   ....  def create @user = user.new(user_params) @user.current_ip=request.env['remote_addr'] @user.save  respond_to |format|   if @user.save     format.html { redirect_to @user, notice: 'user created.' }     format.json { render :show, status: :created, location: @user }   else     format.html { render :new }     format.json { render json: @user.errors, status: :unprocessable_entity }   end end end 

application_controller

 class applicationcontroller < actioncontroller::base  # prevent csrf attacks raising exception.  # apis, may want use :null_session instead.  protect_from_forgery with: :exception   before_filter :set_current_ip   protected  def set_current_ip     @user.current_ip = request.env['remote_addr']  end  end 

here's error i'm getting

enter image description here

traced app/controllers/application_controller.rb:10:in `set_current_ip'

looks me @user isn't set yet in 'def set_current_ip'.

you want (in rails 4)

def set_current_ip   @user = user.where(current_ip: request.remote_ip).first_or_create end  

important note:

tracking user's ip might brittle. ip's can change, , multiple people behind router via nat have same ip.

i don't have great alternative suggestion @ moment, sorry!


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -