如何访问要验证的参数

时间:2016-05-24 10:30:53

标签: ruby-on-rails ruby activerecord

在下面的示例中,有没有办法检索if proc中当前验证的参数的名称?

@Override
    protected String doInBackground(String... params) {
        String strUrl=String.format("%s",SERVER_URL);
        try {

            URL url =new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type","application/json");

            String str="{\"userid\":\"1\"}";
            byte[] outputInBytes = str.getBytes("UTF-8");
            OutputStream os = urlConnection.getOutputStream();
            os.write( outputInBytes );
os.close();


            InputStream stream1=urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(stream1);
        StringBuilder builder = new StringBuilder();
        int chr;
        while((chr=reader.read())!=-1)
        {
            builder.append((char)chr);
        }
        String result=builder.toString();

 return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 return null;
    }

我想避免这种解决方案:

class MyModel < ActiveRecord::Base
  with_options if: proc{|o| "how to retreive the parameter being validated here?"} do
    validates :param_1, presence: true
    validates :param_2, presence: true
  end
end

3 个答案:

答案 0 :(得分:0)

如果您想知道名称和其他数据,例如验证选项,请使用验证器:

应用/验证/ param_validator.rb

ParamValidator < ActiveModel::EachValidator
   def validate_each(record, attribute, value)
      # your validation code here...
   end
end

争论说到自己。

在模型中使用它:

validates :param_1, param: true
validates :param_2, param: true

答案 1 :(得分:0)

如果每个验证与名称相同,您可以迭代它们:

class MyModel < ActiveRecord::Base
  [:param1,:param2].each do |param|
    validates param, presence: true, if: proc{|o| o.need_validation?(param) }
  end
end

答案 2 :(得分:0)

我很确定我的问题没有简单的答案,我会找到另一种方式。