我有一个需要city_id, state_id, and country_id的用户模型。我没有要求用户在他们的配置文件中的每一个,我采取了更现代的方式,并添加了一个位置自动完成。当用户选择一个自动完成选项时,我将city_id存储在表单上的一个隐藏字段中。当表单提交时,我想确保这个城市在我的城市桌子上是一个有效的城市。到目前为止,我的用户控制器中有这个逻辑。我做了这样的事:
def update
# I override the strong parameters here so I can add / remove them if I
# need to.
@user_params = user_params
if @user_params[:city_id]
@city = City.find_by id: @user_params[:city_id]
if @city.present?
@user_params[:city_id] = @city.id
@user_params[:state_id] = @city.state.id
@user_params[:country_id] = @city.country.id
else
# Here I'd like to tell the user they submitted an invalid location
# rather than invalid city, state, country. I don't believe
# I can add custom validation errors in the controller though.
end
end
# Update the user, etc.
end因此,我想有几个问题(我对Rails相当陌生):
city_id, state_id, country_id )变成一个验证(例如:无效位置)。发布于 2015-10-07 12:53:17
因此,删除这些内容后,您只需要验证城市的存在,而不是city_id - http://railsguides.net/belongs-to-and-presence-validation-rule1/。
class User
validates :city, presence: { message: "Location is invalid" }
endhttps://stackoverflow.com/questions/32992399
复制相似问题