[英]What is the way to create a new hash from params?
I'm trying to create a new hash from params
. 我试图从params
创建一个新的哈希。 I'm doing something like this: 我正在做这样的事情:
where_query = { active: true }
where_query[:brand_ids] = params[:brand_ids].split(',') if params[:brand_ids].present?
where_query[:market_id] = params[:market_id] if params[:market_id].present?
Is that okay? 这样可以吗? Or is there a better way to do that? 还是有更好的方法来做到这一点?
I would go with more explicit declaration: 我将使用更明确的声明:
where_query =
{
active: true,
brand_ids: params[:brand_ids].try(:split, ','),
market_id: params[:market_id]
}.select { |_, v| v.present? }
Modern version of the above (Ruby 2.4+ required): 以上版本的现代版本(需要Ruby 2.4+):
where_query =
{
active: true,
brand_ids: params[:brand_ids]&.split(','),
market_id: params[:market_id].presence
}.compact
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.