0

メールボックス システムのビューを実装しています。受信ボックス送信済みメールボックスが必要です。したがって、次のような 2 つのリンクをビューに配置します。

<%= link_to "Inbox", messages_user_path(current_user),:class =>"current", :which_mailbox => "received" %>
<%= link_to "Sentbox", messages_user_path(current_user),:class =>"current", :which_mailbox => "sent" %>

そして、コントローラーが「params[:which_mailbox]」に従って適切なメッセージを取得することを期待しています。そのような:

def fetch_messages
    if params[:which_mailbox] == "received"
      @messages= current_user.received_messages
    else if params[:which_mailbox] == "sent"
      @messages = current_user.sent_messages
    end

    render 'users/messages_page'
end

他のオプションとは対照的に、太字フォントを使用して、選択したメールボックス (つまり、`class="current") のスタイルを設定したいと考えています。

a .current{
    font-weight: bold;    
}

問題は、両方のオプション (受信ボックス/送信ボックス) が上記のコードをclass="current"使用していることです。link_to ..このクラスをアクティブ化/非アクティブ化するにはどうすればよいですか? Javascriptなしでもできますか?それは Rails+ CSS を使用しているだけですか?

編集 これは生成された HTML です。

    <section>
  <a href="/users/1/messages" class="current" which_mailbox="received">Inbox</a>
</section>
<section>
  <a href="/users/1/messages" class="current" which_mailbox="sent">Sent</a>
</section>

がないことに気づきparams[:which_mailbox]ました。キーを初期化する必要があると思いwhich_mailboxます。推奨される場所はどこですか?

4

1 に答える 1

3

ページ全体をリロードするため、ここで JavaScript を使用する必要はありません。適切なクラスをレンダリングするだけです。

<%= link_to "Inbox", messages_user_path(current_user, :which_mailbox => "received"),
                    :class => params[:which_mailbox] == 'received' ? 'current' : '' %>

ロジックをヘルパーに移動することで、このコードを少し乾かすことができます

module MailboxesHelper
  def mailbox_link_class(this_mailbox, current)
    this_mailbox == current ? 'current' : ''
  end

  def mailbox_link(label, type)
    link_to label, messages_user_path(current_user, :which_mailbox => type),
                      :class =>mailbox_link_class(type, params[:which_mailbox])
  end
end

<%= mailbox_link 'Inbox', 'received' %>
<%= mailbox_link 'Sentbox', 'sent' %>
于 2013-10-19T10:56:27.850 に答える