Conditionally setting CSS style from ruby controller

时间秒杀一切 提交于 2019-12-02 19:43:21

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

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])

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
user1575511

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'

You should use JavaScript to do this. I think it's good idea for you to use jQuery instead of pure JavaScript. Here are some examples

http://api.jquery.com/click/

http://api.jquery.com/css/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!