Ruby on Rails 按 ID 以外的字段查找 [英] Ruby on Rails Find By Field other than ID

查看:41
本文介绍了Ruby on Rails 按 ID 以外的字段查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,再次忘记我在 Rails 中的笨拙,但我也没有找到.虽然我认为这个可能是因为好吧..它不存在?

Ok again forget my noobiness in Rails, but I'm not finding this either. Although I think this one might be because well.. it doesn't exist?

好的,所以我还在玩 RoR,我为员工添加了一个控制器,非常简单,只是一个名字、clock_no 和工资.但是如果我不想通过 ID 搜索员工怎么办?对我来说,用户按时钟编号搜索会更容易,但我不知道这是如何工作的.我假设它与这条线有关,更具体地说是 set_employee 线:

Ok so I'm still playing with RoR and I added a controller for employee, pretty simple just a name, clock_no, and wage. But what if I don't want to search for an employee by ID? To me it would be easier for the user to search by clock number, but I'm not figuring out how that works. I am assuming it has something to do with this line, more specificly the set_employee line:

private
# Use callbacks to share common setup or constraints between actions.
def set_employee
  @employee = Employee.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
  params.require(:employee).permit(:name, :clock_no, :wage)
end

但是我可能会离开.

好的,所以我的解决方案最终只是更改模型中的 primary_key:

Ok so my solution ended up being just to change the primary_key in the model:

self.primary_key = 'clock_no'

并将返回设置为json:

And setting the return to json:

def show
@employee = Employee.find(params[:id])
 respond_to do |format|
   format.html
   format.json { render json: @employee }
 end
end

然而,我不认为这真的是最终的解决方案,我的 noobiness 可能再次表现出来,但对我来说似乎有点像曲棍球.如果您想通过说出名称或其他不是主键的内容进行搜索,并且无法像我的情况那样更改主键,那么我的问题是什么?回到文档

HOWEVER, I don't think this is really the end all solution, again my noobiness could be showing, but it seems kinda hockie to me. My hold up would be what if you wanted to search by say name or something else that wasn't the primary key and was not able to change the primary key like in my case? nose back to the docs

推荐答案

Use where:

Employee.where(clock_no: params[:clock_no])

where 返回一个 ActiveRecord 关系,因此如果您需要第一个(并且可能只有 clock_no 唯一的实例),请使用 first,如下所示:

where returns an ActiveRecord relation, so if you need the first (and probably only instance if clock_no is unique), use first, like this:

Employee.where(clock_no: params[:clock_no]).first

这将只执行一个 SQL 查询来获取第一个匹配 clock_no 的 Employee.

This will execute only one SQL query to get the first Employee matching clock_no.

曾经有像 find_by_clock_no 这样的魔法查找器,但从 Rails 4 开始不推荐使用它们,我假设您正在使用.

There used to be magic finders like find_by_clock_no, but those are deprecated as of Rails 4, which I assume you're using.

另请参阅Rails 文档,了解有关 ActiveRecord 查询的更多信息.

Also see the Rails documentation for more info on ActiveRecord queries.

这篇关于Ruby on Rails 按 ID 以外的字段查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆