Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails change background colour in CSS according to database

In my Ruby on Rails application I am trying to allow the user to choose their colour and have this as the sites background.

In my schema I have this preferences table:

create_table "perferences", force: :cascade do |t|
  t.integer  "user_id"
  t.integer  "category_id"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
  t.text     "colour"
end

The CSS background colour is in the following line:

body{line-height:1;height:100%;width:100%;color:#B2BFCB;background:#002952;text-align:center;font-family:"Apercu Regular", Calibri, sans-serif;font-weight:normal;font-style:normal;margin:0;padding:0;}

But I am unsure as to how to update the colour based upon the colour in the database.

I have tried to follow this link: http://blog.hasmanythrough.com/2007/10/18/simpler-than-dirt-restful-dynamic-css But I got the error: undefined method formatted_colour_path for #<#<Class:0x6daa0a8>:0x6881b98>

In the view:

In the perferences controller:

def show
   @colour = Perference.find_by(user_id: session[:user_id]).colour
   respond_to do |format|
        format.html
        format.css
   end
end

Can someone please help. I understand that I need to retrieve the colour from the database and then use this to update the CSS, but I am not sure how to do this.


2 Answers

If you try to change the body background color, then try this:

<body style="background-color: <%= @colour %>">

</body>

But it will make some consequences for you and you will need to go deeper :)

It will be better to do it this way

<body style="background-color: <%= @colour if @colour %>" >

</body>

or just write a helper.

like image 179
Zakhar Day Avatar answered Feb 25 '26 08:02

Zakhar Day


The css file is fixed - you cannot put ruby code inside. An alternative is to do something inline in your application.html.erb:

  <body style="background-color:<%= current_user.preference.color">
  </body>

This of course suppose that the user is always loaded in the "current_user" variable (you can use a condition to treat the "not logged in" case).

like image 24
Martin Avatar answered Feb 25 '26 08:02

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!