Ruby on rails 如何在Rails中路由参数数组

Ruby on rails 如何在Rails中路由参数数组,ruby-on-rails,ruby,Ruby On Rails,Ruby,所以我想通过一组参数传递到Rails中的“testers”路由。我的测试人员表目前如下所示: class CreateTesters < ActiveRecord::Migration[5.1] def change create_table :testers do |t| t.integer :testerID t.string :firstName t.string :lastName t.string :country

所以我想通过一组参数传递到Rails中的“testers”路由。我的测试人员表目前如下所示:

class CreateTesters < ActiveRecord::Migration[5.1]
  def change
    create_table :testers do |t|
      t.integer :testerID
      t.string :firstName
      t.string :lastName
      t.string :country
      t.datetime :lastLogin

      t.timestamps
    end
  end
end
class CreateTesters
我要向其发出请求的url如下所示:
http://localhost:3000/testers?tester_id[]=1和测试人员id[]=2和国家[]=US

我的服务器正确地识别出我传递了一个参数数组,但我的问题是它击中了
索引
路径,只返回数据库中的所有测试程序


如何让Rails将其识别为“show”请求,或者为此类url创建自定义路由?

根据您的评论,理想的做法是使用您的
索引
操作本身

def index
  @testers = Tester.data(params[:tester_ids])
end
在您的
testers.rb
模型中

scope :data, ->(ids) { ids.present? ? where(id: params[:tester_ids].split(',')) : all }
你的url看起来像

http://localhost:3000/testers
适用于所有和


http://localhost:3000/testers?tester_ids=1,2,3
对于筛选测试人员

根据您的评论,理想的做法是使用您的
索引
操作本身

def index
  @testers = Tester.data(params[:tester_ids])
end
在您的
testers.rb
模型中

scope :data, ->(ids) { ids.present? ? where(id: params[:tester_ids].split(',')) : all }
你的url看起来像

http://localhost:3000/testers
适用于所有和

http://localhost:3000/testers?tester_ids=1,2,3
用于视图中的过滤测试仪

= link_to 'Testers', testers_path(ids: @selected_testers.pluck(:id))
在控制器中:

@testers = Tester.find(params[:ids])
与使用
where
相反,
find
确保每个给定ID都有一条记录。因此,如果ID 1337作为
参数[:ids]
数组的一部分进入,并且数据库中没有ID为1337的测试仪,则会引发错误(类似于调用
测试仪。find(1337)
)。

视图中:

= link_to 'Testers', testers_path(ids: @selected_testers.pluck(:id))
在控制器中:

@testers = Tester.find(params[:ids])

与使用
where
相反,
find
确保每个给定ID都有一条记录。因此,如果ID 1337作为
params[:ids]
数组的一部分进入,并且数据库中没有ID为1337的测试仪,则会引发错误(类似于调用
tester.find(1337)
).

这不是传统的
show
url,共享您的路线我的路线目前只是标准路线,我应该在这里添加自定义路线吗?是的..您想显示什么?2个测试人员,因为您通过了2个ID?理想情况下,我希望显示与我通过的ID匹配的每个测试人员,因此这可能是一个很大的数量。在你看来,实现这一点的最佳方式是什么?假设URL正是你想要的,你并不真的想“将其识别为一个显示请求”。同时,我建议不要“为这种url类型创建自定义路由”。但是,我建议您仍然为此使用
索引
操作,但是相应地过滤返回的数据。i、 e在
索引中
方法:
@testers=params[:tester_id]。是否存在?Tester.where(id:params[:Tester_id]):Tester.all
这不是传统的
show
url,共享您的路由我的路由目前只是标准路由,我应该在这里添加自定义路由吗?是的..您想显示什么?2个测试人员,因为您通过了2个ID?理想情况下,我希望显示与我通过的ID匹配的每个测试人员,因此这可能是一个很大的数量。在你看来,实现这一点的最佳方式是什么?假设URL正是你想要的,你并不真的想“将其识别为一个显示请求”。同时,我建议不要“为这种url类型创建自定义路由”。但是,我建议您仍然为此使用
索引
操作,但是相应地过滤返回的数据。i、 e在
索引中
方法:
@testers=params[:tester_id]。是否存在?Tester.where(id:params[:Tester_id]):Tester.all