如何在rails控制器中设置html类属性?

时间:2016-01-03 06:43:22

标签: ruby-on-rails ruby class attributes

我是初学者。我在通知控制器中使用after_action 通知控制器

class NotificationsController < ApplicationController

    layout "posts"

    after_action :read_message, only: [:index]

    def index
        @notifications = Notification.where(:recipient_id => session[:registered_id]).order("created_at DESC")

    end

    def new
        @user = User.find(session[:user_id])
        @notification = @user.notifications.new
    end

    def create
        @user = User.find(session[:user_id])
        @notification = @user.notifications.new notification_params
        if @notification.save
            redirect_to(:controller => "posts", :action => "index")
        else
            render "new"
        end
    end

    private

    def notification_params
        params.require(:notification).permit(:message, :user_id, :recipient_id, :status)
    end

    def read_message
        @notifications = Notification.where(:recipient_id => session[:registered_id]).order("created_at DESC")
        @notifications.read_all
    end

end

通知#index 查看

 <% @notifications.each do |notification| %>
   <div class = message_wrapper>
    <p><%= notification.message %></p>
    <p class = "message_details">from <span><%= notification.user.registered_id %></span></p>
  </div>
 <% end %>

现在在控制器的after_action方法中,我想将&lt; div&gt;(目前使用类 message_wrapper )的类设置为message_wrapper_read。我怎样才能做到这一点?我感谢你的回答。提前谢谢。

1 个答案:

答案 0 :(得分:6)

在控制器中定义类名并不好。它应该适用于视图或帮助程序。

只是你可以做到,

<div class="<%= notification.read? ? 'message_wrapper_read' : 'message_wrapper' %>">