在 jbuilder 中向对象添加属性不起作用

Adding attribute to object in jbuilder doesn't work

在使用 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)
    }
}

在我的员工模型中,我有一个对应的 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 输出中获得 :image_full_url 属性,因为序列化程序对此一无所知。您可以通过以下操作简单地检查一下:

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

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

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