6

以下のコードでは、ユーザーが招待を受け入れた場合、「不参加」の div をクリックして招待を辞退できるようにしようとしています。

そのロジックはうまく機能しますが、ユーザーが招待を受け入れたかどうかに関係なく、「出席していない」div が表示されるように取得しようとしています。

現時点では、ユーザーが招待を受け入れた場合にのみ div が表示されます。

link_to ステートメントを条件付きにする方法はありますが、関係なく div を保持しますか? (つまり、div が常に存在するようにしますが、ユーザーが招待を受け入れた場合にのみリンクになりますか?)

<% if invite.accepted %>
    <%= link_to(:controller => "invites", :action => "not_attending") do %>                             
        <div class="not_attending_div">
             not attending
        </div>
    <% end %>
<% end %>
4

2 に答える 2

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

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

編集:

link_to_ifuses link_to_unlesswhich useslink_toのコード、同じオプションで同じように動作するはずです

  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

<%=
   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
%>

ここでチェックしてください http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_unless

編集:

これはあなたが必要とするものを達成しますか?申し訳ありませんが、質問をよく読んでいません。

<div class="not_attending_div">
   <%= link_to_if invite.accepted, "not attending", (:controller => "invites", :action => "not_attending") %>
</div>
于 2012-06-27T19:26:01.300 に答える
1

ここで答えただけです:条件が満たされた場合にのみ、ブロックを使用して link_to_if を作成する方法は?

とにかくブロックを表示したいが、特定の条件が満たされた場合にのみリンクを追加したい場合は、ブロックを完全にキャプチャして、単純な条件で使用できます。

<% block_content = capture do %>
  <div class="not_attending_div">
    not attending
  </div>
<% end %>

<% if invite.accepted %>
  <%= link_to block_content, controller: :invites, action: :not_attending %>
<% else %>
  <%= block_content %>
<% end %>
于 2021-03-11T11:19:19.107 に答える