检查items_attributes是否有比下面的代码更好的方法?我必须首先检查params [:order],因为有时可能不存在,但我讨厌长条件的外观。
if params[:order] and params[:order][:items_attributes]
对于ruby 2.3,更新,现在您可以使用dig方法
params.dig(:order, :item_attributes)
答案 0 :(得分:1)
您可以创建辅助方法,以便更轻松地使用嵌套哈希。在lib文件夹中创建ruby_ext.rb文件,并编写以下函数:
module RubyExt
module SafeHashChain
def safe(*args)
if args.size == 0 then self # Called without args ...
elsif args.size == 1 then self[args[0]] # Reached end
elsif self[args[0]].is_a?(Hash) then self[args[0]].safe(*args[1..-1])
else nil end # Reached end-value too soon
end
end
end
class Hash; include RubyExt::SafeHashChain; end
在此之后,您可以在嵌套哈希上调用安全方法,如下所示:
params.safe(:order,:items_attributes)
它将从items_attributes返回值。如果order或items_attributes不存在,它将返回nil。
答案 1 :(得分:0)
答案 2 :(得分:0)
您可以使用public class CheckBet {
private String bet;
private ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
private ArrayList<String> userstatuses = new ArrayList<>();
private String status = "open";
private static String url_check_bet = "****";
String resulttest;
private ArrayList<Map<String,String>> passtocheck = new ArrayList<>();
private String currentitem;
private String game;
private onResultListener lister = new onResultListener() {
@Override
public void showResult(HashMap<String, String> finaloutcomes) {
}
};
private String c = "";
JSONArray allgames = null;
private HashMap<String,String> finaloutcomes = new HashMap<String,String>();
public CheckBet(String bet, ArrayList<Map<String,String>> passtocheck) {
this.bet = bet;
this.passtocheck = passtocheck;
}
public HashMap<String,String> checkbetoutcome() {
new LoadAllGamet(onResultListener lister).execute();
return finaloutcomes;
}
public interface onResultListener {
void showResult(HashMap<String,String> finaloutcomes);
}
class LoadAllGamet extends AsyncTask<String, String, String> {
onResultListener listener;
public LoadAllGamet(onResultListener listr) {
listener = listr;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 250000);
//HttpConnectionParams.setSoTimeout(httpParameters, 250000);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_check_bet);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param", bet));
// Log.d("CURRENTITEM", currentitem);
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Responsecxxx:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
client.getConnectionManager().closeExpiredConnections();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
// Log.d("sbsssssssssss", json);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
allgames = jObj.getJSONArray("bets");
// Log.d("WHAT IS MY ARRAY?", allgames.toString());
for (Integer i = 0; i < allgames.length(); i++) {
HashMap<String,String> statuses = new HashMap<>();
JSONObject c = allgames.getJSONObject(i);
JSONArray currentbet = c.getJSONArray("bet");
Log.d("Single array",currentbet.toString());
// Storing each json item in variable
for (Integer a = 0; a < currentbet.length();a++) {
JSONObject d = currentbet.getJSONObject(a);
String Result = d.getString("Result");
String id = d.getString("gid");
Log.d("RESULTS",Result);
statuses.put(id, Result);
}
allbetsmap.add(i, statuses);
Log.d("ddd", statuses.toString());
Log.d("AAA", allbetsmap.get(i).toString());
}
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String param) {
Log.d("SIZE",Integer.toString(allbetsmap.size()));
//ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
//ArrayList<Map<String,String>> passtocheck = new ArrayList<>();
if (allbetsmap.size() == passtocheck.size()) {
for (int i = 0; i < allbetsmap.size();i++) {
if (allbetsmap.get(i).size() == passtocheck.get(i).size()) {
String finaloutcome = "won";
for (String a : allbetsmap.get(i).keySet()) {
String f = allbetsmap.get(i).get(a);
if(f.equals("null")) {
finaloutcome = "open";
}
else if (! (f.equals(passtocheck.get(i).get(a)))) {
finaloutcome = "lost";
break;
}
}
finaloutcomes.put(Integer.toString(i),finaloutcome);
}
}
}
Log.d("Vital",finaloutcomes.toString());
listener.showResult(finaloutcomes);
}
}
// CHANGE THIS AT THE END
}
,如下所示:
@Entity
@Table(name = "user_sessions")
public class UserSession{
@Column(name="uid")
private Long userID;
@Id
@Column(name="access_key")
private String accessKey;
@Column(name="secret_key")
private String secretKey;
public Long getUserID() {
return userID;
}
public void setUserID(Long s) {
this.userID = s;
}`
如果接收方没有响应,则try方法返回try
,而不是引发异常。
希望它有用!
答案 3 :(得分:0)
如果我有这样的问题,我会考虑用这样的东西扩展基本的ruby类Hash
(这只是一个想法)
class Hash
def has_nested_values?(*args)
current_value = self.dup
args.each do |arg|
current_value = current_value[arg]
break unless current_value
end
!!current_value
end
end
,结果是
h[:a] = {b: {c: {d: 1}}}
h.has_nested_values?(:a, :b, :c)
=> true
h.has_nested_values?(:a, :b, :cc)
=> false
PS我在实现中不喜欢dup
,但它可以正常工作
答案 4 :(得分:0)
Params实际上是ActionController::Parameters
的一个实例,并内置了白名单过滤功能。
这样可以做到这样的事情:
# White list for Order params
def order_params
params.require(:order).permit(:items_attributes)
end
// If :order is missing exception, and then filter only permitted.
valid_params = order_params()
// Also make these calls safe without risk for unwanted params
order = Order.new(order_params())
order.save!
答案 5 :(得分:0)
您可能希望使用默认设置获取?
order = params.fetch(:order, {})
if order[:item_attributes]
# ...
end