18

今、私は配列を作成して使用しています:

render :json => @comments

これは単純な JSON オブジェクトでは問題ありませんが、現在、私の JSON オブジェクトにはいくつかのヘルパーが必要であり、すべてが壊れており、コントローラーにヘルパー インクルードが必要であり、解決するよりも多くの問題を引き起こしているようです。

では、この JSON オブジェクトをビューで作成するにはどうすればよいでしょうか。ヘルパーを使用するときに何かをしたり、何かを壊したりすることを心配する必要はありません。現在、コントローラーで JSON オブジェクトを作成している方法は、次のように見えますか? ビューに移行するのを手伝ってください:)

# Build the JSON Search Normalized Object
@comments = Array.new

@conversation_comments.each do |comment|
  @comments << {
    :id => comment.id,
    :level => comment.level,
    :content => html_format(comment.content),
    :parent_id => comment.parent_id,
    :user_id => comment.user_id,
    :created_at => comment.created_at
  }
end

render :json => @comments

ありがとう!

4

3 に答える 3

27

または使用:

<%= raw(@comments.to_json) %> 

html エンコーディング文字をエスケープします。

于 2013-01-27T20:00:48.487 に答える
13

そのコードをヘルパー自体に記述することをお勧めします。次に.to_json 、配列でメソッドを使用します。

# application_helper.rb
def comments_as_json(comments)
  comments.collect do |comment|
    {
      :id => comment.id,
      :level => comment.level,
      :content => html_format(comment.content),
      :parent_id => comment.parent_id,
      :user_id => comment.user_id,
      :created_at => comment.created_at
    }
  end.to_json
end

# your_view.html.erb
<%= comments_as_json(@conversation_comments) %>
于 2011-03-01T23:19:33.363 に答える
7
<%= @comments.to_json %>

トリックも行う必要があります。

于 2011-03-01T23:26:25.707 に答える