Frage

In ruby what's a nice way of choosing which array to traverse conditionally?

If condition is true -> use array 1 if not use array B.

I tried the following but it didn't work.

   <% if  @post.active ?  %>
        <% Post::A_OPTIONS.each do |option|  %>
    <%else %>
        <% Post::B_OPTIONS.each do |option| %>
    <%end%>
      <br><%= radio_button_tag 'option', option, @option == option %>
      <%= option.humanize %>
    <% end %>
War es hilfreich?

Lösung

You should put your business logic into your model. such as

class Post
  def options
    active ? Post::A_OPTIONS : Post::B_OPTIONS
  end
end

then in your view,

<% @post.options.each do |option| %>
  <%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>

In this case, your view is isolated from how the options are generated, and both options logic and view logic are simple and clean

Andere Tipps

What about this?

<% (@post.active ? Post::A_OPTIONS : Post::B_OPTIONS).each do |option|  %>
  <br><%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>

How about you define a method on the Post model that simply returns the correct options? e.g.

class Post < ActiveRecord::Base
  A_OPTIONS = [...];
  B_OPTIONS = [...];

  # other stuff

  def options
    if active
      A_OPTIONS
    else
      B_OPTIONS
    end
  end
end

And then your view will be dead simple:

<% @post.options.each do |option|  %>
  <br><%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top