2

我正在用 Rails 构建一个 API。我用来构建 api 的 gem 是 Grape 和 Rabl。我已经做了很多工作,但现在我必须status在来自 api 的所有 json 响应之前添加标志。我怎么能这样做?

我有这个.rabl文件。

object @current_parent

attributes :first_name => :name
attributes :cell_phone => :mobile
attributes :email
attributes :address

node :day_care do |m| 
{ 
  :name     => current_day_care.name, 
  :address  => current_day_care.address, 
  :phone    => current_day_care.office_phone,
  :website  => current_day_care.website,
  :logo     => current_day_care.logo.url,
  :no_of_child => current_parent.relatives.count
}
end


child :relatives, :object_root => false do |m|
  child :child, :object_root => false do |n|
    attributes :id
    attributes :first_name      =>  :name
    attributes :gender
    attributes :student_stage   =>  :classroom
  end
end

这使得以下输出

{
"parent": {
    "name": "Devan",
    "mobile": "1234567891",
    "email": "testparent1@mail.com",
    "address": "762 Beahan Expressway",
    "day_care": {
        "name": "Brisa Erdman",
        "address": "859 Hermann Summit",
        "phone": "915.758.4580",
        "website": "fisher.info",
        "logo": "/uploads/day_care/logo/1/http%3A/example.com/ally",
        "no_of_child": 2
    },
    "relatives": [
        {
            "child": {
                "id": 1,
                "name": "Lucious",
                "gender": "t",
                "classroom": "PreKindergarten"
            }
        },
        {
            "child": {
                "id": 2,
                "name": "Lilly",
                "gender": "t",
                "classroom": "Toddlers"
            }
        }
    ]
}
}

但我想在打开status之前有一个标志,如下所示parent

{
"status": "Success"
"parent": {
    "name": "Devan",
    "mobile": "1234567891",
    "email": "testparent1@mail.com",

但我不知道如何使用 rabl 来实现这一点。请指导我完成这个。如果不可能,请提供替代解决方案。

4

2 回答 2

2

获取当前parent.rabl文件,并将其用作表示状态的新 rabl 模板中的部分。

 object false
 node :parent do
    partial("parent", :object => @parent)
 end
 node :status  do
   @status
 end

然后从你的控制器调用这个 rabl 文件

于 2014-06-18T17:44:52.420 回答
0

感谢您的回答。我为我的问题找到了另一种解决方案,它似乎适合我的情况,即不需要创建额外的文件并将原始文件parent.rabl称为部分文件。这样我的视图文件数量将相同。看一看

解决方案 parent.rabl 文件

node do |u|
{
  :status => "Success"
}
end
child @current_parent do 

attributes :first_name => :name
attributes :cell_phone => :mobile
attributes :email
attributes :address

node :day_care do |m| 
{ 
  :name     => current_day_care.name, 
  :address  => current_day_care.address, 
  :phone    => current_day_care.office_phone,
  :website  => current_day_care.website,
  :logo     => current_day_care.logo.url,
  :no_of_child => current_parent.relatives.count
}
end

child :relatives, :object_root => false do |m|
  child :child, :object_root => false do |n|
    attributes :id
    attributes :first_name      =>  :name
    attributes :gender
    attributes :student_stage   =>  :classroom
  end
end 
end

通过这种方式,我得到了我想要的结果。

于 2014-06-19T17:38:34.070 回答