【问题标题】:Adding attribute to object in jbuilder doesn't work在 jbuilder 中向对象添加属性不起作用
【发布时间】:2015-08-06 11:19:13
【问题描述】:

在使用 jbuilder 构建 JSON 响应时,我想为我的每个 Employee 对象添加一个属性“image_full_url”。

在我的 jbuilder 文件中,如下所示:

json.branch_companies @companies.select{ |branch| branch.head_company_id == head_company.id}.map{|branch| {
    :branch => branch, 
    :employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" },
    :machine_categories => branch.machine_categories.pluck(:id, :name, :description)
    }
}

在我的 Emplyoee 模型中,我有一个对应的 attr_accessor:

attr_accessor :image_full_url

向 Employee 对象添加属性在控制台上完美运行。

我有问题的部分在这里:

:employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" }

我希望将“image_full_url”属性添加到 emp 对象中,但事实并非如此。 JSON 响应不包含“image_full_path”字段。我究竟做错了什么?有人可以帮忙吗?

【问题讨论】:

  • 你得到什么 JSON 输出?
  • employees: [5] 0: { id: 3 name: "Vanessa" surname: "Woißett" phone_mobile: "+49 1721111111" phone_landline: "+49 711111113" fax: "+49 711111112" email: "vanessa@mail.com" department: "Disposition" company_id: 1 active: true }- 1: { id: 1 name: "Anton" surname: "Massner" phone_mobile: "+49 175655555" phone_landline: "+49 7116555551" fax: "+49 711655555552" email: "anton.massner@gmail.com" department: "Geschäftsführung" company_id: 1 active: true }

标签: ruby-on-rails ruby json jbuilder


【解决方案1】:

当然,您不会在 json 输出中获得 :image_full_url 属性,因为序列化程序对此一无所知。您可以通过执行下一步来简单地检查这一点:

Emplyoee.limit(2).each{|e| e.image_full_url = "asdw"}.as_json

因此,输出不会包含 :image_full_url 属性。如果您希望该属性出现在最终结果中,请添加到下一行:

.as_json(:methods => [:image_full_url])

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2022-01-25
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多