1

I have a very simple model and controller for Location. It has 2 parameters, Longitute and Latitude, and when I create an object using Location.create() it sets the parameters to nil but when I make a call to the parameters they appear.

If I call the @location.latitude from a view I get nil.

Model Location has an attr_accessor :latitude, :longtitude

Controller for Location has standard new and create actions, nothing special, I am using strong params.

params.require(:location).permit(:latitude, :longitude)

console:
irb(main):009:0> loc = Location.create(latitude: 100.1)
   (0.0ms)  begin transaction
   SQL (4.0ms)  INSERT INTO "locations" ("created_at", "updated_at") VALUES (?, ?)       [["created_at", Sat, 26 Jul 2014 02:1
5:50 UTC +00:00], ["updated_at", Sat, 26 Jul 2014 02:15:50 UTC +00:00]]
   (9.0ms)  commit transaction
=> #<Location id: 3, latitude: nil, longitude: nil, created_at: "2014-07-26 02:15:50",     updated_at: "2014-07-26 02:15:50"
>
irb(main):010:0> loc.latitude
=> 100.1

So why is it saving as nil and why does it still have 100.1 in memory, I can't make it save as 100.1

1 Answers1

3

Take out your attr_accessor method. That's causing the issue probably overwriting the getter and setter generated by Rails. Take a look at this and scroll down to the session Overwriting default accessors to better understand why.

Tiago Farias
  • 3,397
  • 1
  • 27
  • 30
  • Actually, it did work but it saves it like so: # i have to add the .to_s to it in order to return "42.1". Is that normal? The value was set to a decimal when I migrated the table in the first place. Just want to know if that's normal. – user3245766 Jul 26 '14 at 12:14
  • When ActiveRecord sees a decimal column, it converts the value to Ruby's BigDecimal so that you can keep the desired number of decimal places. It's the right choice and brings no problem for you. – Tiago Farias Jul 26 '14 at 16:14