0

我正在实现邮箱系统的视图。我想要收件箱和已发送邮箱。因此,我在视图中放置了两个链接,例如:

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