在 Ruby on Rails 中从 collection.map 中排除选项? [英] Exclude option from collection.map in Ruby on Rails?

查看:32
本文介绍了在 Ruby on Rails 中从 collection.map 中排除选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一行:

<%= f.input :state_id, :input_html => {:value => (policy_address.state.name rescue nil)}, :required => true, :collection => states.map {|s| [ s.name, s.id] }, :include_blank => 'Please select'%>

我想从 states.map 集合中排除一个值.我认为这会起作用,但它不起作用:

I want to exclude a value from the states.map collection. I thought that this would work but it doesn't:

<%= f.input :state_id, :input_html => {:value => (policy_address.state.name rescue nil)}, :required => true, :collection => states.map {|s| [ s.name, s.id] unless s.name == "excluded_state" }, :include_blank => 'Please select'%>

我输入了 unless s.name == "excluded_state,但是,再次,它不起作用:

I put in unless s.name == "excluded_state, but, again, it's not working:

我做错了什么?

推荐答案

map 不允许跳过值.您必须首先拒绝不需要的元素.

map doesn't allow to skip values. You have to reject unwanted elements first.

states.reject { |s| s.name == "excluded_state" }.map { |s| [s.name, s.id] }

另一个(更脏的)解决方案是为排除的元素返回 nil 并在结果数组上使用 Array#compact 来删除那些 nil 元素:

Another (dirtier) solution is to return nil for excluded elements and use Array#compact on the resulting array to remove those nil elements:

states.map { |s| s.name == "excluded_state" ? nil : [s.name, s.id] }.compact

这篇关于在 Ruby on Rails 中从 collection.map 中排除选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆