1

I am using this code for displaying data to the f.select tag:

  <%= f.select :status, STATUSES, {}, :class => 'form-control' %>      

The STATUSES hash contains following:

STATUSES = {"A" => 0,
            "B" => 1,
            "C" => 2,
            "D" => 3,
            "E" => 4} 

How to display from the hash only values smaller than than 4 (so "A", "B", "C" and "D")?

Thank you in advance

4 Answers 4

1

Do you mean something like this:

STATUSES.reject { |key, value| value >= 4 }

If so, I would personally create a helper method for it (not sure if you've got access to the STATUSES constant here though):

module StatusHelper
  def statuses_collection
    STATUSES.reject { |key, value| value >= 4 }
  end
end

And in your view:

<%= f.select :status, statuses_collection, {}, :class => 'form-control' %>
Sign up to request clarification or add additional context in comments.

2 Comments

or the other way STATUSES.select { |key, value| value <=3 } :)
STATUSES.select { |key, value| value < 4 } looks better
0

I'd reccomend you setup your hash in the controller if that's possible.

However, if you want to do all the business in the select form code you could try something like this:

      <%= f.select(:status, options_for_select(STATUSES.map { |key, value| [key, value] if value < 4 }), {}, class: 'form-control') %>

Not perfect but that works in Rails 3.

Comments

0

Without any broader context, I would recommend filtering it in the controller.

def your_controller_method @statuses = STATUSES.reject{ |k,v| v >= 4 } end

then in your view:

<%= f.select :status, @statuses, {}, :class => 'form-control' %>

Comments

0

Same as 'reject' above but the conditional looks better

STATUSES.select {|key,value| value < 4}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.