[英]Ruby on rails mysql searches
我对Ruby on Rails完全陌生,我试图搜索一些关系数据库表,试图在Customer表中搜索给定的ID号,然后从结果中查看该客户的sales_rep是谁。 有了这个
@salesrepcust = Customer.find(:all, :conditions => ["id = ?",@data])
给定ID号,我能够找回正确的客户,但我看不到如何在ruby on rails上从这些结果中仅提取一列值,在这种情况下,它将是sales_rep的值,然后将其用作我的@结果
@salesrepcustdata = Salesrep.find(:all, :conditions => ["id = ?", @result])
我已经搜索过此内容,但我想我的措词不正确,因为我无法找到与此相关的任何内容,有人可以帮忙吗?
假设销售代表在“ Customer
表中表示为sales_rep_id
,则可以执行以下操作:
Salesrep.find(Customer.find(@data).sales_rep_id)
find
方法假定您正在寻找id
并且如果只有一个具有该id
项目,则无需指定:all
。
有关全部内容,请参见http://guides.rubyonrails.org/active_record_querying.html
该客户查询可以简化为:
@customer = Customer.find(@data)
您没有提及是否已在Customer和Salesrep之间建立了关系,但是这里有:
# app/models/customer.rb
class Customer < ActiveRecord::Base
belongs_to :salesrep, class_name: 'Salesrep' # => the customers table should have a salesrep_id column
end
# app/models/salesrep.rb
class Salesrep < ActiveRecord::Base
has_many :customers
end
customer_id = 1
@customer = Customer.find(customer_id)
@salesrep = @customer.salesrep
# from the other way, assuming you need both the salesrep and customer:
salesrep_id = 10
@salesrep = Salesrep.find(salesrep_id)
# the following will only find the customer if it's owned by the Salesrep
@customer = @salesrep.customers.find(customer_id)
选择单个列非常简单; 您可以尝试这样的事情:
@salesrepcustids = Customer.where(id: @data).select(:id)
这将生成SELECT id FROM ...
语句。
现在您可以执行以下操作:
@salesrepcustdata = Salesrep.where(id: @salesrepcustids)
这将生成带有这些ID的SELECT...IN
语句。
(您可能会发现在模型中建立适当的ActiveRecord has_many
和belongs_to
关系,或任何适当的关系会更容易。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.