Search code examples
cssruby-on-railsattributeslink-to

Rails change html element attribute in link_to


I'm creating a Previous Page button. This is my button:

<li>
<%= link_to "Previous Page", titles_path(:page => @previous_page), class:"button big previous" %>
</li>

If page is 0, it should be disabled. My new button should be like this:

<li>
<%= link_to "Previous Page", titles_path(:page => @previous_page), class:"disabled button big previous" %>
</li>

I mean, I should use if-else in link_to, and according to the if-else my code should change class of my button.

How can I do that?


Solution

  • Use conditional as Tony suggested, but Tony's approach is a bit flawed because 0 is not false in Ruby. Try this

    = link_to 'Previous Page', titles_path(page: @previous_page), class: "#{(@previous_page == '0')  ? 'disabled' : ''} button big previous"
    

    Hope that helps!