如何在Rails中创建Jquery闪现消息而不是默认的Rails消息?

5

我希望在我的页面顶部而非标准的Rails闪现消息中创建自定义的jQuery消息。我想在我的赞同按钮附近创建一个闪现消息。

我的控制器:

def vote_up
  @post = Post.find(params[:id])
  current_user.up_vote(@post)
  flash[:message] = 'Thanks for voting!'
  redirect_to(root_path, :notice => 'Tak for dit indlæg, det er nu online!')
rescue MakeVoteable::Exceptions::AlreadyVotedError
  flash[:error] = 'Already voted!'
  redirect_to root_path
end

我的观点:

<% @posts.each do |post| %>
  <h1><%= post.titel %></h1>
  <p><%= post.body_html %></p>
  <p><%= link_to 'Vote up', stem_op_path(post.id) %> BRUGERNAVN: <%= post.user.username %> | UPVOTES: <%= post.up_votes %> | DOWN VOTES: <%= post.down_votes %> OPRETTET: <%= post.created_at.strftime("%d %B") %><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></p>
  </tr>
<% end %>

这是两种不同的情况:页面加载时顶部的闪存消息(就像在SO上)和ajax-upvote上的闪存消息? - jimworm
5个回答

20

Groupon式通知,采用带有透明通道的背景色以获得最佳外观。

#rails controller   
flash[:notice] = "Login successful!"



#rails helper
module ApplicationHelper
  def flash_notifications
    message = flash[:error] || flash[:notice]

    if message
      type = flash.keys[0].to_s
      javascript_tag %Q{$.notification({ message:"#{message}", type:"#{type}" });}
    end
  end

end



#rails layout
<%= flash_notifications -%>



#javascript code
(function( $, undefined ) {
    $.notification = function(options) {
        var opts = $.extend({}, {type: 'notice', time: 3000}, options);
        var o    = opts;

        timeout          = setTimeout('$.notification.removebar()', o.time);
        var message_span = $('<span />').addClass('jbar-content').html(o.message);
        var wrap_bar     = $('<div />').addClass('jbar jbar-top').css("cursor", "pointer");

    if (o.type == 'error') {
          wrap_bar.css({"color": "#D8000C"})
        };

        wrap_bar.click(function(){
            $.notification.removebar()
        });

        wrap_bar.append(message_span).hide()
            .insertBefore($('.container')).fadeIn('fast');
    };


    var timeout;
    $.notification.removebar    = function(txt) {
        if($('.jbar').length){
            clearTimeout(timeout);

            $('.jbar').fadeOut('fast',function(){
                $(this).remove();
            });
        }   
    };


})(jQuery);



#css
.jbar{
    height:50px;
    width:100%;
    position:fixed;
    text-align:center;
    left:0px;
    z-index:9999999;
    margin:0px;
    padding:0px;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=92); 
    opacity: 0.92;
    -moz-opacity: 0.92;
    -moz-box-shadow: #555 0px 0px 5px;
    box-shadow: #555 0px 0px 5px;
}

.jbar-top{
    top:0px;
}

.jbar-bottom{
    bottom:0px;
}

.jbar-content{
    line-height:46px;
    font-size: 18px;
}

.jbar-top a.jbar-cross{
    top:8px;    
}

.jbar-bottom a.jbar-cross{
    bottom:8px;
}

我无法在rails3 + haml上使其工作。我只能在我的HTML视图中看到文本%Q{$.notification({ message:"my message", type:"notice" });}。实际上,我不知道$.notification应该翻译成什么。 - dgilperez
%Q 只是 Ruby 的字符串引用方法,你可以使用其他任何方法。你只需要将 $.notification 作为 JS 代码执行即可。 - Anatoly

2

这有点取决于您所说的自定义JQuery消息的含义。例如,如果您有一个部分,它接收一条消息并以某种方式呈现它,则可能会有类似以下的内容:

<% if flash[:message] %>
    <%= render :partial => "path_to_success_partial", :locals => {:message => flash[:message]} %>
<% elsif flash[:error] %>
    <%= render :partial => "path_to_error_partial", :locals => {:message => flash[:message]} %>
<% end %>

<% @posts.each do |post| %>
    <h1><%= post.titel %></h1>
    <p><%= post.body_html %></p>
    <p><%= link_to 'Stem op', stem_op_path(post.id) %> BRUGERNAVN: <%= post.user.username %> | UPVOTES: <%= post.up_votes %> | DOWN VOTES: <%= post.down_votes %> OPRETTET: <%= post.created_at.strftime("%d %B") %><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></p>
    </tr>
<% end %>

然后在您的局部文件中,您可以编写类似以下内容的代码:

<script type="text/javascript">
    $(document).ready(function() {
         //put stuff into your div here
         var errordiv = ".error";
         $(errordiv).css("border", "2px solid pink");
         $(errordiv).html(message);
         $(errordiv).animate({
             //some animation
         }, 500); 
    });
</script>
<div class="error"></div>

需要注意的是,如果您想在应用程序中使用闪存消息,您应该将它们放在某个局部文件中,并将其添加到全局视图 layouts/application.html.erb 中,以便您可以将功能通用化。


您的解决方案会使闪存消息出现在投票链接旁边吗?还是只会出现在顶部?(就像我使用的闪存消息助手一样) - Rails beginner
你可以把那个if语句放在任何地方,我只是假设你想把它放在顶部。 - vinceh
我希望错误信息出现在投票链接旁边,而不是在顶部。 - Rails beginner
您在所有帖子上都显示了“赞同”按钮,那么页面上不会有很多这样的按钮吗? - Chris Barretto
就像我之前说的那样,如果你想让if语句紧挨着你的“赞同”链接,那么你可以把它放在那里。 - vinceh
但是我会得到很多错误消息吗?有许多帖子,闪存错误标记将被重复。我在考虑是否可能将错误 div 定位到鼠标所在位置。 - Rails beginner

1
如果你想要类似于this这样的东西。那么你可以使用这个gem

我的意思是像这样的东西:http://www.amino.dk/buzz/Forside 尝试给一个帖子点赞 - Rails beginner
这是一个非常好的宝石,如果文档也能提供英文版本就更好了。 - Rails beginner

0

我认为使用redirect_to root_path会很难得到一个优雅的解决方案。假设你的root_path控制器动作与vote_up在同一个控制器中,我会这样做:

# Assuming your root_path points to index
def index
  @posts = Post.all
end

def vote_up
  # You'll need to set up all the prerequisites for your index view here
  @posts = Post.all

  @post = @posts.detect {|post| post.id == params[:id]}
  begin
    current_user.up_vote(@post)
    redirect_to(root_url, :notice => 'Tak for dit indlæg, det er nu online!')
  rescue MakeVoteable::Exceptions::AlreadyVotedError
    @post.errors.add_to_base("Already voted!")
    render 'index'
  end
end

然后将您的视图设置为如下:

<% @posts.each do |post| %>
  <% if post.errors.present? %>
    <div class="posterror"><%= post.errors.full_messages.to_sentence %></div>
  <% end %>
  <h1><%= post.titel %></h1>
  <p><%= post.body_html %></p>
  ...
<% end %>

接下来使用CSS为div.posterror进行样式设计,或者使用jQuery添加一些炫酷特效,很多jQuery工具提示插件都是一个不错的起点。

最棒的是将vote_up改为AJAX方式。


-1

您可以使用 flash[:notice] 或 flash[:error] 在视图中获取闪存消息,并在任何您喜欢的位置显示它。例如:

<p id='notice'>
   <%=flash[:notice]%>
</p>

我已经在使用那个闪现消息。但是我想创建一个靠近vote_up链接的Jquery闪现消息,而不是Rails默认的闪现消息。 - Rails beginner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接