Ruby-on-rails Rails 3 - 按名称而不是 id 查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5572266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:51:48  来源:igfitidea点击:

Rails 3 - Find by name instead of id

ruby-on-railsruby-on-rails-3

提问by rmp

I'm trying to learn RoR, building my first app, a basic inventory application. I've tried searching around but could not find the correct syntax, so I thought I would ask.

我正在尝试学习 RoR,构建我的第一个应用程序,一个基本的库存应用程序。我试过四处搜索,但找不到正确的语法,所以我想我会问。

Here's my set up:

这是我的设置:

Model

模型

class Item < ActiveRecord::Base
belongs_to :supplier

class Supplier < ActiveRecord::Base
has_many :items

Items Controller

物品控制器

@items = Item.find_all_by_supplier_id '1'

This will return the data that I want, but I was hoping to input the supplier name into the controller so that if the ID does not match up it will still work properly.

这将返回我想要的数据,但我希望将供应商名称输入控制器,以便如果 ID 不匹配,它仍然可以正常工作。

Hope that's enough info, thanks!

希望有足够的信息,谢谢!

回答by Gazler

You could invert your method bit and try:

您可以反转您的方法位并尝试:

@items = Supplier.find_by_name('THE NAME').items

Rails creates dynamic find_by_* and find_all_by_* methods for searching. Instead of retrieving items by the supplier_id, I recommend you let rails do this for you with the associations you have set up as in the code snippet above. Internally, this still uses the supplier_id, but rails is handling the process instead of you.

Rails 为搜索创建了动态的 find_by_* 和 find_all_by_* 方法。我建议您不要通过供应商 ID 检索项目,而是让 Rails 使用您在上面的代码片段中设置的关联来为您执行此操作。在内部,这仍然使用供应商 ID,但 rails 正在处理该过程,而不是您。

The inverse of this is also possible, so if you have an item and want the supplier, you can do:

反过来也是可能的,所以如果你有一个项目并且想要供应商,你可以这样做:

Item.find(1).supplier

回答by fl00r

@items = Item.joins(:suplier).where(:suplier => { :name => "Suplier name" })

回答by ImranNaqvi

Supplier.find_by_colname(params[:name])

Where colnameis the name of Supplier table columnin which we want to check our parameter value. In rails we can just append column name with the find_by_as shown above and rails will show you it's magic ;) . Here is the reference in Doc

我们要检查参数值colname的名称Supplier table column在哪里。在 rails 中,我们可以find_by_如上所示添加列名,rails 会向您展示它的神奇之处 ;) 。这是文档中的参考