【问题标题】:How to add class in controller如何在控制器中添加类
【发布时间】:2016-03-15 18:50:02
【问题描述】:

我想在控制器中添加一个类来更改 if 函数通知中出现的消息颜色

这是我的控制器

def send_password
    @user=User.find_by_email(params[:user][:email])
    if @user.present?
      @user.send_reset_password_instructions
      flash[:notice] = "Reset password instructions have been sent to #{@user.email}."
      redirect_to reset_password_path, notice: "Reset password instructions have been sent to #{@user.email}."
    else
      return redirect_to reset_password_path, notice: "User is not available."
    end
  end
end

请帮忙。

我尝试过并以这样的形式给出,但它不起作用。

<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: {method: :post}) do |f| %>
   <% if f.error_notification == 'User is not available' %>
       <h1 class='reset-error-message'><%= f.error_notification %></h1>
   <% else %>
       <h1 class='reset-success-message'><%= f.error_notification %></h1>
   <% end %>`

然后在控制器中我尝试这样也不起作用

if @user.present?
  @user.send_reset_password_instructions
  flash[:notice] = "Reset password instructions have been sent to #{@user.email}."
  redirect_to reset_password_path, notice: "Reset password instructions have been sent to #{@user.email}.",class:"reset-success-message"
else
  return redirect_to reset_password_path, notice: "User is not available., class:"reset-error-message"
end

【问题讨论】:

  • 请告诉我们您已经尝试过什么。

标签: ruby-on-rails ruby ruby-on-rails-3 model-view-controller


【解决方案1】:

您最好对不同的通知使用不同的 Flash 消息类别:

# Use flash *notice*
redirect_to reset_password_path, notice: "Reset password instructions have been sent to #{@user.email}."

# Use flash *alert* (error)
return redirect_to reset_password_path, alert: "User is not available."

在您的布局或视图中,您现在可以使用自己的 CSS 类渲染每个 Flash:

<% flash.each do |name, msg| -%>
  <%= content_tag :div, msg, class: name %>
<% end -%>

【讨论】:

  • 这里的“名字”是什么? flash.each 做 |name, msg|
  • name 是 Fl​​ash 类型,也是将使用的 CSS 类(通知或警报)的名称。
  • 如何在此处添加我的班级名称?我想在失败时添加“reset_error_message”作为类名,在成功时添加“reset_success_message”作为类名
  • 我尝试了与您给出的相同的方法。但是当我检查元素时,只有警报类即将到来通知不会到来
猜你喜欢
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 2012-02-18
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2016-10-30
相关资源
最近更新 更多