Model 虚拟属性(自动完成关联)获取旧值如果留空,如何正确更新?
我试着做和你一样的事情 所以我有一个属性名为的模型城市Model 虚拟属性(自动完成关联)获取旧值如果留空,如何正确更新?,model,autocomplete,attributes,ruby-on-rails-4,Model,Autocomplete,Attributes,Ruby On Rails 4,我试着做和你一样的事情 所以我有一个属性名为的模型城市 class City < ActiveRecord::Base has_many :collection_points end …还有一个模型采集点 class CollectionPoint < ActiveRecord::Base belongs_to :city ... def city_name city.try(:
class City < ActiveRecord::Base
has_many :collection_points
end
…还有一个模型采集点
class CollectionPoint < ActiveRecord::Base
belongs_to :city
...
def city_name
city.try(:name)
end
def city_name=(name)
self.city = City.where(name: name).first_or_create if name.present?
end
我的控制器如下所示:
class Admin::CollectionPointsController < ApplicationController
before_filter :authenticate
before_action :set_collection_point, only: [:show, :edit, :update, :destroy]
...
# PATCH/PUT /collection_points/1
# PATCH/PUT /collection_points/1.json
def update
respond_to do |format|
if @collection_point.update(collection_point_params)
format.html { redirect_to [:admin, @collection_point], notice: 'Collection point was successfully updated.' }
format.json { render json: @collection_point, status: :accepted }
else
format.html { render action: 'edit' }
format.json { render json: @collection_point.errors, status: :unprocessable_entity }
end
end
end
...
private
# Use callbacks to share common setup or constraints between actions.
def set_collection_point
@collection_point = CollectionPoint.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def collection_point_params
params.require(:collection_point).permit(:id, :name, :collection_type_id, :online, :street, :district, :zip, :city_name, :latitude, :longitude, :organisation_id, :direction)
end
end
创建一个新的收集点工作得非常好,但是当我将编辑视图中的输入字段留空并提交时,它只接受旧值而不是nil
谢谢你的时间 你指的是所有的输入字段吗?@David你是什么意思?试试City。其中:name、name.first\u或\u createIt没有区别,仍然有相同的问题。我将city_name的输入字段值保留为空,但rails只接受旧city_name值而不是nil,并将其保存到db。