Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute ruby code in a link in Haml

Tags:

ruby

haml

I want to have a "delete user" link in a normal Activerecord table, but I can't figure out how to wrangle the inline ruby in haml.

I have this:

   %tbody
    - @users.each do |user|
      %tr
        %td= user.name
        %td= user.login
        %td
          %a
            %img{:src => '../images/delete.png', :title => 'Delete user'}

How do I make the

- user.destroy

be a clickable link in Haml?

like image 276
thermans Avatar asked Dec 29 '22 20:12

thermans


2 Answers

I think you want

%tbody
 - @users.each do |user|
   %tr
     %td= user.name
     %td= user.login
     %td
       = link_to image_tag('delete.png', :title => "Delete #{user}"), user_path(user), :method => :delete)

See ActionView::Helpers::UrlHelper#link_to

Or, if you're not using ActionPack,

%tbody
  - @users.each do |user|
    %tr
      %td= user.name
      %td= user.login
      %td
        %a{:href => "/users/#{user.id}?_method=delete"}
          %img{:src => '/images/delete.png', :title => "Delete #{user}"}
like image 179
James A. Rosen Avatar answered Jan 14 '23 13:01

James A. Rosen


Here's a good tip on handling inline Ruby in HAML. It even allows you to have punctuation (notice the "!") after links (meaning it's truly inline).

From the HAML FAQ:

If you’re inserting something that’s generated by a helper, like a link, then it’s even easier:

%p== I like #{link_to 'chocolate', 'http://franschocolates.com'}!
like image 26
Magne Avatar answered Jan 14 '23 15:01

Magne