Rails: changing an element class from a controller

I format the menu so that the title is colored differently after clicking on it. I would like to use the same haml template for each view and I would like the controller to change the class of a particular html element. How to configure html target elements from a controller and add a class to them?

Here is an example:

The haml:

%tr %th %a#name-header= link_to "Name", people_path({:sort => 'by_name'}) %th Date %th Description %th More Info 

Controller:

 def index case params[:sort] when "by_name" @people = Person.find(:all, :order => "name") #How can I change the class of the th element here else @people = Person.all end end 

Thanks!

+4
source share
2 answers

Controller code

 def index @people, @klass = case params[:sort] when "by_name" [Person.order(name: :asc), "foo"] else [Person.all, "bar"] end end 

Code view

The css class for tr is foo or bar based on the sort parameter:

 %tr{class: @klass} %th= link_to "Name", people_path(sort: "by_name"), id: "name-header" %th Date %th Description %th More Info 
+5
source

You cannot directly change the class of an html element from a controller.

It looks like your class will be based on params[:sort] . You can check this in the template to create the appropriate css class. It would probably be easier to move this to an assistant.

+1
source

Source: https://habr.com/ru/post/1401077/


All Articles