验证隐藏的字段数据

时间:2015-10-07 12:35:59

标签: ruby-on-rails

我有一个需要$query = $this->db->query("SELECT value FROM mydb WHERE ID='example'"); // Check if there are any rows returned from the query if ($query->num_rows > 0) { // Here you are getting array of your row. $row = $query->row; // Now here you are getting specific column value from our row into your variable. $variable = $row['yourcolumnname']; // Here we are echo our variable to test it. echo $variable; } 的用户模型。我没有在他们的个人资料中询问用户这些,而是​​采用了更现代的方式,并添加了一个位置自动完成功能。当用户选择自动填充选项时,我将city_id, state_id, and country_id存储在表单上的隐藏字段中。当表格提交时,我想确保这个城市是我城市桌上的有效城市。截至目前,我的用户控制器中有这个逻辑。我做这样的事情:

city_id

所以我猜有几个问题(我对Rails很新):

  1. 我应该把这个逻辑放在哪里以便重用?
  2. 这是我正在努力完成的正确方法吗?
  3. 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 之类的一组验证如何进入一个验证,如:无效的位置。

1 个答案:

答案 0 :(得分:0)

删除后,您只需要验证城市的存在,而不是city_id - http://railsguides.net/belongs-to-and-presence-validation-rule1/

class User
  validates :city, presence: { message: "Location is invalid" }
end