Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a conditional link_to statement in Rails?

In the code below, I'm trying to make it so that, if a user has accepted an invite, they'll be able to click on the "not attending" div to decline the invite.

That bit of logic works fine, but I'm trying to get it so the "not attending" div shows up regardless of whether the user has accepted the invite.

Right now, the div only appears if the user has accepted the invite.

Is there a way to make the link_to statement conditional, but preserve the div regardless? (That is, make it so the div is always present, but is only a link if the user's accepted the invite?)

<% if invite.accepted %>
    <%= link_to(:controller => "invites", :action => "not_attending") do %>                             
        <div class="not_attending_div">
             not attending
        </div>
    <% end %>
<% end %>
like image 571
Adam Templeton Avatar asked Jun 27 '12 19:06

Adam Templeton


1 Answers

<%= link_to_if invite.accepted ... %>

http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if

Edit:

link_to_if uses link_to_unless which uses link_to 's code, it should work the same with the same options

  def link_to_unless(condition, name, options = {}, html_options = {}, &block)
    if condition
      if block_given?
        block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
      else
        name
      end
    else
      link_to(name, options, html_options)
    end
  end

Example

<%=
   link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
     link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
   end
%>

check it here http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_unless

Edit:

Does this achieve what you need. Sorry, for not reading the question better.

<div class="not_attending_div">
   <%= link_to_if invite.accepted, "not attending", (:controller => "invites", :action => "not_attending") %>
</div>
like image 144
Sully Avatar answered Sep 22 '22 01:09

Sully