简体   繁体   English

从 RoR 中的同一个 model 获取两个索引请求的最佳方法是什么?

[英]What is the best way to GET two index requests from the same model in RoR?

I have a WorkSpace model that has_many reviews.我有一个有很多评论的 WorkSpace model。 In the reviews model I have a rating column using integers for a numbered rating.在评论 model 中,我有一个使用整数进行编号评级的评级列。

I would like to list all of the work_spaces from a WorkSpace model and also list the top 5 work_spaces based on the overall review rating of the models.我想列出 WorkSpace model 中的所有work_spaces ,并根据模型的整体评价列出前 5 个work_spaces

In my controller I have an index method that works well for retrieving all of the work_spaces.在我的 controller 中,我有一个索引方法,可以很好地检索所有工作空间。

WorkSpacesController 工作区控制器
class WorkSpace < ApplicationRecord
  belongs_to :user
  has_many :reviews, dependent: :delete_all
  acts_as_votable

  scope :by_average_for, ->(column) {
    joins(:reviews)
      .group('work_spaces.id')
      .order("AVG(reviews.#{column}) desc")
      .having("AVG(reviews.#{column}) > 4", column) if column
  }

  def top_avg_rating
    WorkSpace.by_average_for(:rating).limit(5)
  end

I have been successful in retrieving the top rated work_spaces by placing my logic in my work_space model.通过将我的逻辑放在我的 work_space model 中,我成功地检索了评分最高的 work_spaces。

WorkSpace 工作区
class WorkSpace < ApplicationRecord belongs_to:user has_many:reviews, dependent: :delete_all acts_as_votable scope:by_average_for, ->(column) { joins(:reviews).group('work_spaces.id').order("AVG(reviews.#{column}) desc").having("AVG(reviews.#{column}) > 4", column) if column } def top_avg_rating WorkSpace.by_average_for(:rating).limit(5) end

I send this info out through my serializer and it's easily accessible, but it's attached to every work_space that's indexed.我通过我的序列化程序发送此信息,它很容易访问,但它附加到每个索引的工作空间。 I don't need to have the info attached to each and every work_space.我不需要将信息附加到每个工作空间。 I would ultimately only need to GET this info when the application initially loads.我最终只需要在应用程序最初加载时获取此信息。

I figured it would be easy enough to just run a GET request for that info in the WorkSpaces Controller, so I tried adding this method to the controller.我认为只需在 WorkSpaces Controller 中对该信息运行 GET 请求就足够简单了,因此我尝试将此方法添加到 controller。

WorkSpacesController 工作区控制器
 def top_rated @work_spaces = WorkSpace.by_average_for(:rating).limit(5) render json: @work_spaces end

I tried to write a new route for it, but I had trouble figuring out how to do that.我试图为它写一条新路线,但我不知道该怎么做。 I tried this in my routes.我在我的路线上试过这个。

 get 'top_rated', to: 'work_spaces#top_rated'

with my path being http://localhost:4741/work_spaces/top_rated我的路径是http://localhost:4741/work_spaces/top_rated

This responded with:这回应:

Started GET "/work_spaces/top_rated" for::1 at 2020-04-26 23:35:38 -0400 Processing by WorkSpacesController#show as / Parameters: {"id"=>"top_rated"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."token" = $1 LIMIT $2 [["token", "3bbddce2b4c8f7e6a79a62f56ad9229a"], ["LIMIT", 1]] WorkSpace Load (0.4ms) SELECT "work_spaces".* FROM "work_spaces" WHERE "work_spaces"."id" = $1 LIMIT $2 [["id", 0], ["LIMIT", 1]] [active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.06ms) Completed 404 Not Found in 16ms (Views: 2.6ms | ActiveRecord: 3.1ms)开始 GET "/work_spaces/top_rated" for::1 at 2020-04-26 23:35:38 -0400 WorkSpacesController#show as /参数处理: {"id"=>"top_rated"} 用户负载 (0.4ms) SELECT "users".* FROM "users" WHERE "users"."token" = $1 LIMIT $2 [["token", "3bbddce2b4c8f7e6a79a62f56ad9229a"], ["LIMIT", 1]] WorkSpace Load (0.4ms) SELECT "work_spaces ".* FROM "work_spaces" WHERE "work_spaces"."id" = $1 LIMIT $2 [["id", 0], ["LIMIT", 1]] [active_model_serializers] 渲染 ActiveModel::Serializer::Null 和 ZFAE8A9257E154175DAZ4193 0.06ms) 完成 404 Not Found in 16ms (Views: 2.6ms | ActiveRecord: 3.1ms)

This seems to me that the parameters are looking for an ID for showing a work_space.在我看来,参数正在寻找用于显示工作空间的 ID。

I replaced my original index method with the top_rated method and that worked well, but I can't seem to get both indexes working at the same time.我用 top_rated 方法替换了我原来的索引方法并且效果很好,但我似乎无法让两个索引同时工作。

Should I just leave the logic in the model?我应该将逻辑留在 model 中吗? I'm wondering what the best practice is for this type of logic.我想知道这种逻辑的最佳实践是什么。 Thanks in advance for any help or guidance you can give me.提前感谢您能给我的任何帮助或指导。

Update更新

I got this to work thanks to NemyaNation .感谢NemyaNation ,我得到了这个工作。

I changed my route in routes.rb to get '/work_spaces/top_rated' => 'work_spaces#top_rated'我在 routes.rb 中更改了路线以get '/work_spaces/top_rated' => 'work_spaces#top_rated'

This didn't work until I moved the route above some of my other routes.直到我将路线移到其他一些路线之上,这才奏效。

 # frozen_string_literal: true Rails.application.routes.draw do resources:reviews, except: %i[new edit] get '/work_spaces/top_rated' => 'work_spaces#top_rated' resources:work_spaces, except: %i[new edit] # RESTful routes resources:examples, except: %i[new edit] resources:work_spaces do member do put 'like', to: 'work_spaces#upvote' put 'unlike', to: 'work_spaces#downvote' get 'likes', to: 'work_spaces#like' end end # Custom routes post '/sign-up' => 'users#signup' post '/sign-in' => 'users#signin' delete '/sign-out' => 'users#signout' patch '/change-password' => 'users#changepw' patch '/update-user' => 'users#update' end

Not 100% sure why that is... but using the rake routes to check my available routes was extremely helpful and led me to hunt down a better understanding of routes.不是 100% 确定为什么会这样……但是使用rake routes检查我的可用路线非常有帮助,并让我更好地了解路线。

A couple of links I found helpful:我发现一些有用的链接:

https://guides.rubyonrails.org/routing.html https://guides.rubyonrails.org/routing.html

https://devhints.io/rails-routes https://devhints.io/rails-routes

Your path to the top_rated definition is wrong.您到 top_rated 定义的路径是错误的。

Change your routes.rb to show:更改您的 routes.rb 以显示:

get 'work_spaces/top_rated', to: 'work_spaces#top_rated'

Use the command rake routes to show you how to properly construct your routes.使用命令rake routes向您展示如何正确构建您的路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM