[英]When and where to aggregate or perform calculations on data in RESTful Rails API
我想知道在Rails或MVC中是否应该采用一般方式来聚合数据或对其进行计算(例如,抓取电影脚本的十个随机行,或者相互乘以十个产品价格)。 具体来说,我正在尝试在我的应用程序中执行第一个示例(10行电影脚本)。
我正在使用Rails 5.2+。 到目前为止我尝试过的是在我的ScriptLinesController
创建一个实例方法getRandomLines
。 但是我不确定是否应该使用show方法并在客户端聚合数据,或者我是否应该将该方法放在模型ScriptLine
我已经使用Postman测试了以下路线并且它可以工作,但它似乎是错误的方法:
#My routes.rb:
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'script_lines/test', to: 'script_lines#getRandomLines'
end
我的控制器看起来像这样:
class ScriptLinesController < ApplicationController
def index
render json: ScriptLine.all
end
def show
scriptLine = ScriptLine.find_by(id: params[:id])
render json: scriptLine
end
def getRandomLines
numLines=rand(0..9)
nineLines = []
numLines.times do
id_num = rand(1..ScriptLine.last.id)
nineLines << ScriptLine.find_by(id: id_num)
end
render json: nineLines[0]
end
end
我的模型看起来像这样:
class ScriptLine < ApplicationRecord
validates :line_number, presence:true
belongs_to :script
end
最后我的架构如下所示:
create_table "script_lines", force: :cascade do |t|
t.string "line_number"
t.string "line"
t.bigint "script_id"
t.index ["script_id"], name: "index_script_lines_on_script_id"
end
总而言之,是在控制器中创建方法并指定这些方法的路由,以正确的方式以RESTful方式聚合/执行数据计算? 特别是我想知道7条标准RESTful路由是否是唯一允许的路由,或者是否可以使用ad-hoc路由来操作符合REST原则的数据。
这是我的第一个问题,如果要求太多或太模糊,请提前道歉,因此会相应修改。
这是一个非常广泛的设计问题,所以我只想给出一个思考的一般指针列表:
models/
具有相应的类)完全适合于更自然地映射到客户端所寻找的内容。 random
在/script_lines/random
,然后控制器方法random
。 就个人而言,如果我并不过分担心RESTful-ness,我会向ScriptLinesController添加一个新动作,如下所示:
class ScriptLinesController < ApplicationController
def random
num_lines = rand(0..9)
render json: ScriptLine.order("RANDOM()").limit(num_lines)
end
end
随着random
函数随着时间的推移变得越来越复杂,我会考虑将它移到ScriptLine
模型中。 如果添加的更复杂性与“随机脚本行集合”的概念在逻辑上相关,我会将该代码移到另一个单独的模型并创建一个新的控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.