简体   繁体   English

访问器和update_attributes

[英]accessors and update_attributes

I have a model with a location attribute, it's a array of two elements; 我有一个带有location属性的模型,它是两个元素的数组; latitude and longitude. 纬度和经度。 I define the accessors for the location like this 我为这样的位置定义访问器

class Address
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Spacial::Document

    field :location,        :type => Array,    spacial: {lat: :latitude, lng: :longitude, return_array: true }


    #accessors for location


    def latitude
        location[0]
    end

    def latitude=( lat )
        location[0] = latitude
    end

    def longitude
        location[1]
    end

    def longitude=( lng )
        location[1] = lng
    end
    attr_accessible :location, :latitude, :longitude

end

here is the controller code 这是控制器代码

def create
        @address = Address.new(params[:address])
        if @address.save
            redirect_to :action => 'index'
        else
            render :action => 'new'
        end
    end

    def update
        @address = Address.find(params[:id])

        if @address.update_attributes(params[:address])
            redirect_to :action => 'index'
        else
            render :action => 'edit'
        end

    end

and at the view level 在视图级别

<%= f.hidden_field :latitude%>
<%= f.hidden_field :longitude%>

these hidden field are manipulated via js, and that is ok. 这些隐藏的字段是通过js处理的,没关系。 I saw it view developers tools 我看到了它查看开发人员的工具

Here are the parameters the controller receives 这是控制器接收的参数

"address"=>{"latitude"=>"-38.0112418", "longitude"=>"-57.53713060000001", "city_id"=>"504caba825ef893715000001", "street"=>"alte. brown", "number"=>"1234", "phone"=>"223 4568965"}, "commit"=>"Guardar", "id"=>"504cacc825ef893715000006"}

Note that the latitude and longitude parameters changed and thats ok, but this change it's not saved to the mongodb 请注意,纬度和经度参数已更改,没关系,但是此更改并未保存到mongodb中

So, The values for latitude and longitude are not saved. 因此,不会保存纬度和经度的值。 Is there any instruction my code is missing? 我的代码缺少指令吗?

Thanks in advance. 提前致谢。

--- edit --- -编辑-

here are the working accessors 这是工作访问器

    def latitude
        location[0]
    end

    def latitude=( lat )
        self.location = [lat,self.location[1]]
    end

    def longitude
        location[1]
    end

    def longitude=( lng )
        self.location = [self.location[0], lng]
    end

When you want to set a field of your database, use self always safer and it's a good habit. 当您要设置数据库的字段时,请总是更安全地使用self ,这是一个好习惯。

Second thing, you have to use the argument you pass to the setter. 第二件事,您必须使用传递给setter的参数。

Resulting code: 结果代码:

def latitude
  location[0]
end

def latitude=( lat )
  self.location[0] = lat
end

def longitude
  location[1]
end

def longitude=( lng )
  self.location[1] = lng
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM