helpisgood helpisgood - 2 years ago 71
Ruby Question

How to use 'dynamic CSS' in Rails

I'm new to Ruby on Rails and I'm trying to extract information I have from certain fields in a database and use them as means of styling.

For example, I have a height and width field in my 'Student' database. I wish to extract the height field content and width field content as parameters for my CSS file to set the height and width respectively of a div tag.

I am having a lot of trouble doing this. I have linked my stylesheet in the view index.html.erb by:

<%= stylesheet_link_tag 'students' %>

which is under assets/stylesheets/students.scss

I am not sure how to proceed.

Answer Source

Seems like an inline style would work fine here. In your ERB, in your student divs, just do:

<% @students.each do |student| %>
  <div style="height: <%= student.height %>px; width: <%= student.width %>px;">
    <!-- other student stuff -->
<% end %>

It's either this or generating a unique CSS class for every student first, then using it in each div.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download