[英]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.