【问题标题】:Array of hashes where hash is returned by a function in jbuilderjbuilder中的函数返回散列的散列数组
【发布时间】:2016-03-04 04:50:29
【问题描述】:

我有一个 PORO TutorProfileHandler,它有一个函数 json,它返回一个哈希值。

class TutorProfileHandler

    def initialize(opts)
        @profile = opts[:tutor_profile]
    end

    def json
        tutor = @profile.tutor
        return {
            id: tutor.id,
            first_name: tutor.first_name,
            last_name: tutor.last_name.first + '.',
            school: @profile.school,
            avatar: @profile.avatar.url,
            bio: @profile.bio,
            academic_level: @profile.academic_level,
            headline: @profile.headline,
            major: @profile.major,
            rate: @profile.rate,
            rating: @profile.rating,
            courses: JSON.parse(@profile.courses),
            video_url: @profile.video_url
        }
    end
end

在我的index_tutor_profiles.json.jbuilder,我想生成

{
   tutor_profile: [{id: 1, ...}, {id: 2, ...}, ...],
   tutor_sum: 20
}

但是当我这样做时

json.tutor_profiles (@tutor_profiles) do |profile|
    TutorProfileHandler.new({tutor_profile: profile}).json
end

json.tutor_sum @tutor_sum

它给了我一个tutor_profiles 的空数组。

但是,如果我将所有内容从 TutorProfileHandler.json 移动到 jbuilder 文件,它就可以工作。如何在 jbuilder 数组中显式包含 TutorProfileHandler.json 返回的哈希?

注意:这会返回一个数组,但会创建一个新的键值对array:

json.tutor_profiles json.array(@tutor_profiles) do |profile|
    TutorProfileHandler.new({tutor_profile: profile}).json
end

结果:

{
   array: [{id: 1, ...}, {id: 2, ...}, ...],
   tutor_profile: [],
   tutor_sum: 20
}

【问题讨论】:

  • json 构建器是 DSL。一个人不应该将哈希传递给构建器,一个人应该明确声明像last_name @profile.last_name 这样的DSL。
  • @mudasobwa 如果我也有一个具有相同键值对的show_tutor_profile.json.jbuilder,那么干的方法是什么?
  • 我自己从未使用过 builder,因为我没有找到优雅的 DRY 模式。可能唯一的方法是有一个 lambda,它在准备好的哈希上调用 public_send key, value。顺便说一句,hash.to_json 有什么问题?

标签: ruby-on-rails ruby json jbuilder


【解决方案1】:

有一个丑陋的做法:

json.tutor_profiles @tutor_profiles do |profile|
    tmp_json = TutorProfileHandler.new({tutor_profile: profile}).json
    json.(tmp_json, *(tmp_json.keys))
end

我认为最好的做法是直接嵌套在模型中。您可以从其 github 页面获取更多信息。

【讨论】:

  • 它仍然返回一个空数组。
  • 谢谢,但我只是决定完全跳过 jbuilder 并将逻辑粘贴到控制器中,在那里呈现 json 哈希。
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 2015-04-21
  • 2012-06-12
  • 2010-11-02
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多