Ruby on rails Rails-集合为空时替代渲染的语法
我有下面的代码,它不工作Ruby on rails Rails-集合为空时替代渲染的语法,ruby-on-rails,ruby-on-rails-4,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) %>"); 在\u image\u co
$('div').html("<%= escape_javascript (render partial: 'comments/image_comment',
collection: @image_comments || render html: "<strong>Not Found</strong>".html_safe) %>");
在
\u image\u comments.html.erb
文件中执行以下操作:
<% if @image_comments %>
==> your current partial here
<% else %>
<strong>Not Found</strong>
<% end %>
==>您当前所在的位置
未找到
只要使用其中一种方法就很容易了
<%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(“”);
$('div').html(“未找到””)%>”;
或
$('div').html("<%= !@image_comments.empty? ? escape_javascript(render partial: 'comments/image_comment', collection: @image_comments) : '<strong>Not Found</strong>' %>");
$('div').html(“”);
得到什么错误,你能发布吗?Ruby实际上对空格很敏感;如果你要在方法调用中使用括号,请不要在方法名称和开始括号之间留任何空格。你能在show_comments.js.erb
->$('div').html()中试试这个吗;
@7urkm3n似乎不起作用。我得到一个语法错误,指向j render
@muistooshort在方法名消除错误后的空格,但是当我的集合为空时,我没有得到要呈现的条件的第二部分。这似乎不起作用。如果我正在使用集合,并且集合为空,由于集合中没有成员,rails不会对分部执行任何操作吗?如果集合中有任何内容,则将呈现分部(如前所述)。如果没有,则将呈现“未找到”“。因此,您只需调用
,最底层的内容是,如果您有一个空集合,渲染将返回nil,因此我认为可以使用上面的答案。
<%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>' %>");