2017-04-12 3 views
0

I次のコードを持っており、それは私も試したRailsの - コレクションが空の場合、代替のための構文は、レンダリング

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

を働いていない私は、いくつかのために速記render @image_commentsを使用することはできません

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

この私はレールを行う際に理由理由は、私が代わりに_comments.html.erb_image_comments.html.erbを命名していると私はなぜ知らない部分を使用しています。

エラー

SyntaxError (/show_comments.js.erb:4: syntax error, unexpected tLABEL, expecting keyword_do or '{' or '(' 
[email protected]_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='... 
+0

なって何のエラー、uが投稿できますか? – 7urkm3n

+0

Rubyは実際には空白に敏感です。メソッド呼び出しで括弧を使用する場合は、メソッド名と開始括弧の間にスペースを入れないでください。 –

+0

'show_comments.js.erb' - >' <%data = @image_comments?>でこれを試すことができますか? @ が見つかりません。 ""%> $( 'div').html(<%= data%>); ' – 7urkm3n

答えて

0

このような_image_comments.html.erbファイルにあなたの条件を実行します。

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

それはうまくいかないようです。私がコレクションを使用していてコレクションが空の場合、コレクションにメンバーがないため、レールは部分的に何もしません。 – user4584963

+0

コレクションに何かがある場合は、部分的に(以前と同じように)レンダリングします。もしあなたが何も持っていなければ、あなたは "見つからない"という表現をします。だから、あなたは 'コールするだけで済みます。<%= escape_javascript(部分的にレンダリング:コメント/ image_comments ')%>' –

+0

この[セクション]の一番下(http://guides.rubyonrails.org/layouts_and_rendering.html#レンダリングコレクション)は、空のコレクションレンダリングがある場合、レンダリングはnilを返すので、上記のようなものを使用することができると考えた理由です。 – user4584963

0

だけのいずれか一つのアプローチを使用し、その非常に簡単。

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

OR

$('div').html("<%= [email protected]_comments.empty? ? escape_javascript(render partial: 'comments/image_comment', collection: @image_comments) : '<strong>Not Found</strong>' %>"); 
関連する問題