【问题标题】:Render Json with methods and several objects使用方法和几个对象渲染 Json
【发布时间】:2016-10-14 00:41:01
【问题描述】:

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

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

效果很好!但是,我需要在这个 json 中放入更多没有 photo_url 方法的对象。

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

我收到了这个错误:

品牌的未定义方法“photo_url”

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails json methods


    【解决方案1】:

    您应该在model 中尝试相同的操作,而不是在控制器中创建 json。检查下面的示例代码,我添加了一个简单的 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
    

    希望能帮到你:)

    【讨论】:

    • 太棒了!谢谢! :D 让控制器中的 json 困扰我。我会把它移到模型上,它会很漂亮! :D
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2014-07-10
    • 2013-08-03
    • 1970-01-01
    • 2021-07-24
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多