【问题标题】:how to: Rails respond_to json using exact same rabl template?如何:Rails respond_to json 使用完全相同的 rabl 模板?
【发布时间】:2012-07-13 19:25:12
【问题描述】:

我有两个动作,其中渲染最终应该使用相同的 rabl 模板输出 json,但目前,它们每个都有一个具有自己名称的模板

dashboard.json.rabl 和 batch_create.json.rabl

它们是完全相同的,如何在 batch_create 模板中指定使用仪表板的模板?

谢谢!

EDIT #包括控制器的两个动作和它们的 rabl 视图

line_items_controller.rb

def dashboard
  @line_items ||= LineItem.limit(1000).all.to_a
  pids = [1,2,3,4,5]
  @projects = Project.only(:id, :name).where(:_id.in => pids).to_a
  @users    = User.only(:first, :last, :role, :company_id).all.to_a
  @companies= Company.where(:_id.in => @users.map(&:company_id)).to_a
  @specs    = Spec.where(:specable_id.in => pids).to_a
    spec_ids= @specs.map { |e| e.id }
  @contact_infos = ContactInfo.where(:infoable_id.in => spec_ids).to_a    end
  gon.rabl

  respond_to do |format|
    format.html
    format.json
  end
end

def batch_create
  @line_items = LineItem.where(:_id.in => params[:line_item_ids]).to_a

  # else same as #dashboard
end

app/views/line_items/dashboard.json.rabl 与 app/views/line_items/batch_create.json.rabl 相同

object false

child @projects => :projects do
  attributes :id, :name
end

child @companies => :companies do
  attributes :id, :name
end

child @users => :users do
  attributes :id, :full, :company_id
end

child @specs => :specs do
  attributes :id, :style, :due_at_note
end

child @contact_infos => :contact_infos do
    attributes :info, :infoable_id
end

child @line_items do
  attributes :id, :title, :dashboard_length, :dashboard_created_at, :original_file_url, :project_id
end

【问题讨论】:

    标签: ruby-on-rails rabl


    【解决方案1】:

    您是否尝试在 batch_create.json.rabl 中使用它:

    extends '<insert_object_name>/dashboard'
    

    【讨论】:

    • 嗨,TC,我试过了,但是返回的对象被包装在一个数组中。所以在我的dashboard.json.rabl中,它返回{“foo”:“bar”},如果我在我的batch_create.json.rabl中扩展'line_items/dashboard',我会返回[{“foo”:“bar "}]。您是否知道如何将其排除为对象数组?谢谢
    • 你能用 rabl 视图和控制器操作更新问题吗?
    • 整个响应包含在 [] 中还是仅包含 line_items 子项?
    • 最后一行的第三个应该是“child @line_items => :line_items do”并且整个响应没有包含在[]中
    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多