3

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.

2 Answers 2

4

If the styling is database driven, you should not rely on sprockets which generates static stylesheets during deployment.

A simple solution is to build css content using ERB.

<style>
.students-container {
  height: "<%= @height.to_i %>px",
  width: "<%= @width.to_i %>px"
}
</style>

You can extract out the style node into a partial and reuse it in multiple templates.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. So I should use 'general CSS' only for styling which does not rely on Ruby parameters? When I have tried implementing this, it doesn't give me the correct results. I have used a ruby for loop to go through each student, and I want to retrieve the height and width from the database of that student (already integer values) and set the div height/width but it is not updating accordingly.
The 'general CSS' ie. CSS that is processed through Rails asset pipeline is generated once during deployment and remains static thenafter. While you can use ruby through .css.erb extension - the css generated once will not change automatically when the database value changes - unless you manually precompile. Can you expand your question with what goes wrong. Specifically it would be helpful if you could attach the content of style tag in the html from browser's page source.
3

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 -->
  </div>
<% end %>

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

2 Comments

This works, but when I put it in <style></style> in the head tag, I have issues with the height and width properties setting properly.
Why put it in the <style> tag? Just put it in the divs.

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.