使用方法和多个对象渲染Json

时间:2016-10-14 00:41:01

标签: ruby-on-rails json methods

在Rails上我可以用这样的额外方法渲染一些json:

render json: {
  user: user
}, methods: :photo_url

工作得很好!但是,我需要在这个没有photo_url方法的json中放置更多的对象。

render json: {
  brand: brand,
  user: user
}, methods: :photo_url

我收到了这个错误:

  

品牌

的未定义方法'photo_url'

那么,我怎样才能将此方法仅插入用户对象?

谢谢!

1 个答案:

答案 0 :(得分:1)

不要在控制器中创建json,而应该在model中尝试相同的方法。检查下面的示例代码,我添加了一个简单的URL ... routes。 还可以使用url_helpers在json文件中添加路由。

###a part of create action in controller=>USERS_CONTROLLER.RB
    ##code is wrapped in respond_to block
    @new_picture = @hall.pictures.new(:picture=>pic,:title=> "Test")
    if @new_picture.save
        format.json { render json: {files: [@new_picture.to_fileupload_success] }}
    end

###return json from model=>USER.RB/PICTURE.RB
def to_fileupload_success
 {
      "name" => read_attribute(:picture_file_name),
      "size" => read_attribute(:picture_file_size),
      "url" =>  picture.expiring_url.to_s,
      "thumbnailUrl" => picture.expiring_url.to_s,
      "success" => "Picture uploaded",
      "showeUrl" => Rails.application.routes.url_helpers.user_picture_path(self)

    }
end

希望它能帮助:)