Rails/Ruby delete_if
I have a select tag nested in my form and I am needing to delete an item from my options_for_select array if it equals the word English
开发者_C百科code:
<%= fields_for :users_languages do |u| %>
<div class="field">
<%= u.label :Assign_Languages %><br />
<%= select_tag :language_id,
options_for_select(Language.all.collect {|lang|
[lang.english, lang.id].delete_if {lang.english == "English"}
}, @lang_list),
:multiple => true,
:prompt => 'Select Language' %>
</div>
<% end %>
Problem: The above code works fine, but for some reason the first option is still shown in the mutli-select producing a blank select option. Is there anyway to get rid of the select option and its value? Am I even doing this correctly?
Thanks for all the help in advance!
You can do it using a collect and a reject.
Language.all.collect { |lang| [lang.english, lang.id] }.reject { |(lang, id)| lang == 'English' }
Not sure how to do it using just collect.
I realize this is a year old, but for the sake of future googlers...
Rather than inlining SQL, you might be better off with a named scope:
scope :not_english, where("english != 'English'") # Rails 3
or
named_scope :not_english, :conditions => "english != 'English'" # Rails 2
which will let you do:
options_for_select(Language.not_english.collect {|lang| [lang.english, lang.id]})
That is easier to read, more expressive, and not depending on some magic database id.
Cheers!
(PS: Also, you may want to consider updating your schema so the name of the db column isn't confused with it's value. May I suggest language.name, rather than language.english?)
It looks like your selection is actually returning an empty array as the first element. Try pulling out the unwanted option first:
Language.all.reject {|lang| lang.english == "English}.collect {|lang| [lang.english, lang.id]}
Thanks for the reply guys! What I ended up doing was handle it in my query
code:
<%= fields_for :users_languages do |u| %>
<div class="field">
<%= u.label :Assign_Languages %><br />
<%= select_tag :language_id, options_for_select(Language.find(:all, :conditions => "id != 1").collect {|lang| [lang.english, lang.id]}, @lang_list),:multiple => true, :prompt => 'Select Language' %>
</div>
<% end %>
the first row in the database will always be the same so this was easy to do in the query... although the suggestions above will come in handy in the future! Thanks again!
精彩评论