【问题标题】:RoR: Method to return a statement in a json format?RoR:以 json 格式返回语句的方法?
【发布时间】:2023-04-07 09:33:02
【问题描述】:

我正在寻找一种以 JSON 格式返回此语句的方法。

def statement
   total = 0
   bonus points = 0
   result = 'Car rental for #{@name.to_s}\n'
    for r in @rentals
      this_amount = 0
      case r.car.style
      when Car::SUV
          this_amount += r.days_rented * 30
      when Car::HATCHBACK 
          this_amount += 15
      if r.days_rented > 3
          this_amount += (r.days_rented - 3) * 15
      end
      when Car::SALOON
          this_amount += 20
      if r.days_rented > 2
          this_amount += (r.days_rented - 2) * 15
      end
      else
    end

        if this_amount < 0
            bonus_points -= 10
        end

        bonus_points = bonus_points + 1
        if r.car.style == Car::SUV && r.days_rented > 1
            bonus_points = bonus_points + 1
        end

        result += r.car.title.to_s + "," + this_amount.to_s + "\n"
        total += this_amount
    end

    result += "Amount owed is " + "#{total.to_s}" + "\n"
    result +="Earned bonus points: " + bonus_points.to_s
    result
end

我需要向我的类添加什么方法才能以 JSON 格式返回此语句?谢谢。

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-5


    【解决方案1】:

    最简单的方法

    return {:result => result}
    

    在您的方法结束时。

    但如果您使用控制器向用户显示数据,我更愿意在我的控制器方法中使用.to_json

    【讨论】:

    • 谢谢。我的模型中有这种方法。您认为它应该在控制器中吗?这里的语法是 def json_statement return {:result => result} end ?那行得通吗?这是我习惯的语法,谢谢。
    • 真是一团糟。您需要将计算奖金或您正在做的任何事情的业务逻辑与您希望如何呈现/序列化它分开。现在它真的只属于重构。
    • 你可以从控制器调用这个模型方法。在模型方法中有业务逻辑,并在那里准备响应并将其返回给控制器。然后从控制器你可以呈现这样的 json 响应:render json: { result: response }
    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2010-12-28
    • 2014-06-21
    • 1970-01-01
    • 2022-11-11
    • 2011-06-11
    • 2013-08-06
    相关资源
    最近更新 更多