Leahcim
Leahcim

Reputation: 41969

Rails: float the right type for this column?

I'm trying to save an IP to a database of everyone who visits the home page of my app. I added an IP model/table with a ip:float column and did the following in the index.

 def index
    ..........

    ipmodel  = Ip.new
    @ip = request.ip
    ipmodel.ip = @ip
    ipmodel.save

  end

When I checked the database in the console, it gave me this

#<Ip id: 1, ip: 127.0, created_at: "2012-05-08 02:27:14", updated_at: "2012-05-08 02:27:14"> 

So, since I'm visiting from localhost, it's 127.0. However, I'm wondering why it's only 4 digits, since an the ip address is

127.0.0.1

1) I'm guessing that it trimmed off some of the decimals because "float" isn't the right type. What should I use instead to record the whole IP?

2) Also, as I'm a bit of a newbie/hack, I'm assuming the code in the index can be improved. I'd appreciate if you'd help me improve the code to collect and save the IP.

Upvotes: 2

Views: 1665

Answers (1)

Matt Huggins
Matt Huggins

Reputation: 83289

You'll want to save the IP address as a string. For IPv4, I believe the max length is 15 characters (###.###.###.###). If you want to account for IPv6, then you'll need to account for a max length of 45 characters. See this related question that explains why it's 45 characters.

Upvotes: 1

Related Questions