Rails - 集合为空时替代渲染的语法

时间:2017-04-12 21:28:45

标签: ruby-on-rails ruby-on-rails-4

我有以下代码但它无效

$('div').html("<%= escape_javascript (render partial: 'comments/image_comment',
                                  collection: @image_comments || render html: "<strong>Not Found</strong>".html_safe) %>");

我也试过这个

$('div').html("<%= escape_javascript (render (partial: 'comments/image_comment',
                                  collection: @image_comments) || render (html: "<strong>Not Found</strong>".html_safe)) %>");

我出于某种原因无法使用速记render @image_comments,因为当我执行rails时,我使用的是部分名为_comments.html.erb而不是_image_comments.html.erb,我不知道为什么。

错误

SyntaxError (/show_comments.js.erb:4: syntax error, unexpected tLABEL, expecting keyword_do or '{' or '('
...@image_comments || render html: "<strong>Not Found</strong>"...
...                               ^
/show_comments.js.erb:4: syntax error, unexpected ')', expecting keyword_end
...ot Found</strong>".html_safe) );@output_buffer.safe_append='...

2 个答案:

答案 0 :(得分:0)

_image_comments.html.erb文件中执行这样的条件:

<% if @image_comments %>
  ==> your current partial here
<% else %>
  <strong>Not Found</strong>
<% end %>

答案 1 :(得分:0)

很容易使用任何一种方法。

<%if !@image_comments.empty?%>
    $('div').html("<%= escape_javascript (render partial: 'comments/image_comment', collection: @image_comments) %>");
<%else%>
    $('div').html("<strong>Not Found</strong>") %>");
<%end%>

$('div').html("<%= !@image_comments.empty? ? escape_javascript(render partial: 'comments/image_comment', collection: @image_comments) : '<strong>Not Found</strong>' %>");