Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally setting CSS style from ruby controller

I'm trying to dynamically change (if it got clicked) a normal table header (which is a link) to another defined CSS class 'th.hilite'. This link simply sorts this column and the header should got highlighted every time a user sorts the list.

The view where the class in question should be changed, looks like this:

%table#mytable
  %thead
    %tr
      %th= link_to 'Title', mytable_path(:sort => 'title'), :id => 'title_header'

My question is simply: How and where could I dynamically set the class to %th.hilite if the header is clicked?

like image 375
Proghero Avatar asked Mar 10 '12 13:03

Proghero


4 Answers

You can bind it from the view directly:

%th{:class => ("hilite" if @sort == "title")}= link_to 'Movie Title'...

However, you will also have to declare the @sort instance variable in your controller, and set it to either title or release, according to which column you are sorting. (i.e. @sort = params[:sort])

like image 65
Szilard Muzsi Avatar answered Sep 30 '22 08:09

Szilard Muzsi


Be careful not to put logic (even conditionals) in your views if you can find a way around it. In order to avoid this common mistake, you need to make good use of the params and session hashes and set appropriate variables in controllers

# In your view
%th{:class => @title_header}= link_to 'Title', my_path(:sort => 'title'), :id => 'title_header'

# In your controller
sort = params[:sort] || session[:sort]
if sort == 'title'
  ordering = {:order => :title}
end
like image 21
mehtunguh Avatar answered Sep 30 '22 08:09

mehtunguh


BTW as long as values of your param match column name - no need to code each one

def index
    @by=params[:by]
    @movies = Movie.order(params[:by]).all
  end
like image 23
webstranger Avatar answered Sep 30 '22 08:09

webstranger


Javascript or jquery is not required..

The following HAML will work

%th{:class=>('title' == @sortby)?'hilite':""}= link_to  'Movie Title', movies_path(:sort => 'title'), :id => 'title_header'
like image 34
user1575511 Avatar answered Sep 30 '22 09:09

user1575511