在Rabl中显示子元素和Parent

时间:2015-04-18 16:38:10

标签: json ruby-on-rails-4 rabl rails-api

我用rabl创建了rails-api应用程序作为json builder模板。我的模型在下面

class Course < ActiveRecord::Base
  belongs_to :department
end

class Department < ActiveRecord::Base
  has_many :courses
end

我作为json返回课程。我的课程有标题和学分以及DepartmentId。我现有的兔子是

collection @courses => :courses
attributes :id, :Title, :Credits 

但我需要在Department表中包含部门名称。所以我的json是

{
courses: 
  {
    course: {
      id: 1045
      Title: "Calculus"
      Credits: 4
    }-
  }-
  {
    course: {
        id: 1050
        Title: "Chemistry"
        Credits: 3
   }-
  }
}
}

我需要在Credits之后添加部门作为下一个对象。是普通的rails app,我可以在html中输入 course.department.Name 。但是如何在拉布尔?请指导我

1 个答案:

答案 0 :(得分:0)

我建议在课程模型中添加委托

def start_upload
  @forecasts = Forecast.all
  Forecast.export_to_s3(@forecasts.to_json) 
end

def self.export_to_s3(data)
  # ---AWS configs ---
  Aws.config = { :access_key_id => aws_access_key, :secret_access_key => aws_secret_access_key, :region => aws_region }

  tmpfile = Tempfile.new('forecast')
  tmpfile.write(data)
  tmpfile.close

  s3 = Aws::S3::Client.new(region:aws_region)
  resp = s3.put_object(
           :bucket => aws_bucket,
           :key => aws_bucket_key_forcast,
              :body => IO.read(tmpfile)
            )
  tmpfile.unlink
end

然后添加

delegate :name, to: :department