Search code examples
ruby-on-railsrubyrails-geocoder

Rails 3, saving data without a form


How do I save information from my site http://yocoro.com/public into my database ? just by going to the page

PS: I'm using 2 gems geocoder and user-agent to optain this information.

//controller
class PublicController < ApplicationController  
  def index  
      @time = Time.now  
      @user_agent = request.env['HTTP_USER_AGENT']  
  end  
end

//view
<%= request.ip %>
<%= request.location.city %>  
<%= request.location.country_code %>  
<%= @user_agent %>

Solution

  • Based on input from @meager I was able to trim this way down.

    Create a model and the appropriate table to go with it

    rails generate model location ip:text city:text country:text user_agent:text
    

    Then in your index action just put the info together and store it:

    def index
      @ip = ip_param
      # Here is where you use the IP address and the geocoder gem to gather the 
      # info from the ip address. Then create the location object and save it.
      @location = Location.new
      @location.ip = @ip
      @location.city = city
      @location.country = country
      @location.user_agent = request.env['HTTP_USER_AGENT']
      @location.save
    end
    

    here is how I finally did it.. I try this before it didn't work but I finally understand why, my old code had "@location = location.new" the letter -l- was lower case and rails was giving me an error after I change to "@location = Location.new" bingo bango it worked!!!.

    thank you so much to everyone.!!!

      @location = Location.new
      @location.ip = request.ip
      @location.city = request.location.city
      @location.country = request.location.country_code
      @location.user_agent = request.env['HTTP_USER_AGENT']
    
      if @location.save
        flash[:notice] = 'Location save'
      else
        flash[:notice] = 'Location did not save' 
      end