【问题标题】:rails - how to render a JSON object in a viewrails - 如何在视图中呈现 JSON 对象
【发布时间】:2011-07-06 21:41:01
【问题描述】:

现在我正在创建一个数组并使用:

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

谢谢!

【问题讨论】:

  • 对“需要几个助手”有点困惑,什么助手,做什么?
  • html_format 是用户 simple_format 和 auto_link 的助手。这就是所有麻烦所在。

标签: ruby-on-rails json ruby-on-rails-3 actionview


【解决方案1】:

或使用:

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

转义任何 html 编码字符。

【讨论】:

  • 经过测试,看起来很安全,例如"&lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt; 变为 "\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e"
【解决方案2】:
<%= @comments.to_json %>

也应该这样做。

【讨论】:

    【解决方案3】:

    我建议您在帮助程序本身中编写该代码。然后只需使用.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) %>
    

    【讨论】:

    • 等等...在帮助器内部是否意味着它可以使用诸如 simple_format 之类的东西而无需包含?
    • 如果我这样做是因为 html_format 使用 simple_format 和 auto_link 是个问题?
    • 我假设您现在已经找到了自己的答案 - 但是是的,您不需要在助手中明确包含其他助手。注意:这要求您的 ApplicationController 具有 helper :all(默认)。
    猜你喜欢
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多