2013-11-01 163 views
0

我完全是Ruby on Rails的新手,我試圖通過一些關係數據庫表進行搜索,我試圖在Customer表中搜索給定的ID號,然後從結果中查看誰該客戶的sales_rep是。有了這個Ruby on rails mysql搜索

@salesrepcust = Customer.find(:all, :conditions => ["id = ?",@data]) 

我能給出有身份證號找回正確的客戶,但我沒有看到如何在導軌上,然後從這些結果拉只有一個列的值,在這個紅寶石這將是該值SALES_REP,然後用它作爲我的@result用於

@salesrepcustdata = Salesrep.find(:all, :conditions => ["id = ?", @result]) 

...我已經尋找這一點,但我猜我不是措辭,因爲我不能夠找到專門就這事,誰能幫助?

回答

0

假設銷售代表在Customer表表示爲sales_rep_id你可以這樣做:

Salesrep.find(Customer.find(@data).sales_rep_id) 

find方法假定你正在尋找id,如果有隻是一個與id項目,有沒有需要指定:all

這在http://guides.rubyonrails.org/active_record_querying.html

0

所有討論客戶查詢可以簡化爲:

@customer = Customer.find(@data) 

你不會,如果你已經設置的客戶和銷售代表之間的關係提,但這裏有雲:

# 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) 
0

選擇單個列非常簡單;你可以嘗試這樣的:

@salesrepcustids = Customer.where(id: @data).select(:id) 

這將產生一個SELECT id FROM ...聲明。

現在你可以這樣做:

@salesrepcustdata = Salesrep.where(id: @salesrepcustids) 

這將產生一個SELECT...IN語句,這些ID。

(您可能會發現更容易建立適當的ActiveRecord has_many和你的模型belongs_to關係,或任何的關係是適當的。)

+0

我正在嘗試使用代碼編譯錯誤 /rails1時編譯錯誤/app/views/example/salesrepdisplay.html.erb:21:語法錯誤,意外':',期待')' @salesrepcust = Customer.where(id:@data).select(:id) 我試過swtich圍繞:在第一個ID給我 未定義的方法'在哪裏爲# user2793027

+0

這很奇怪。你使用的是什麼版本的ruby/rails?簡寫散列語法應該在任何版本的Ruby 1.9.x中都可用。另外,你的模型是否繼承自ActiveRecord :: Base? – struthersneil

+0

只是爲了闡明「簡寫散列語法」,例如,將'id:@ data'更改爲':id => @ data'。 HTH –