alex alex - 3 months ago 10
Ruby Question

ruby change color of label if conditional

I'am just start to learn code (and english .. ) and I have a prob with ruby conditional . :O

I have an array, " Category" who depending to "Publication" post.

and i would like that the color of label to my category change in fonction to catgeory ?

( sorry for my english i work for learn ^^ )

It's a part of my simple form for for post a product ( it 's false it's just for show my idea )

<%= f.input :Category, collection:[" Application ", "Nature" ,"Design", "Science"], prompt: "Choisissez votre categorie"%>**

Its a part of my index view to all my product

<% if Category["Nature"]? %>
<span class="label label-info">
<h6><%= publication.Category %></h6>
<% else if Category["Tech"]? %>
<span class="label label-sucess">
<h6><%= publication.Category %></h6>

thx for help


An alternative to the above suggestion would be to create a helper method.

def publication_label(category)
  colors = {
    'Nature'      => 'label-info',
    'Tech'        => 'label-success',
    'Application' => 'label-info'

  content_tag(:span, class: "label #{colors[category]}") do
    content_tag(:h6, category)

(Since you are probably also new to rails, you might be able to put that into /app/helpers/publications_helper.rb).

With that helper in place, your view can be as simple as:

<%= publication_label publication.Category %>