[英]RoR - SQLite3::SQLException: no such column: - Rails not appending _id to generated query
[英]Rails Database Query ROR
首先,我對ROR還是陌生的,我正在嘗試提出一種更有效的方法來對我的數據表進行數據庫查詢。
我的模特協會
class Store < ActiveRecord::Base
has_many :surveys
has_many :customers
end
...
class Survey < ActiveRecord::Base
belongs_to :store
end
...
class Customer < ActiveRecord::Base
belongs_to :store
end
在我的數據表中
<tbody>
<% @store.surveys.each do |survey| %>
<tr class="th-container table-fixer">
<td><%= find_customer_id(survey.email).nil? ? survey.first_name : link_to(survey.first_name, store_customer_path(@store, find_customer_id(survey.email))) %></td>
<td><%= get_ltv(survey) %></td>
</tr>
<% end %>
</tbody>
find_customer_id和get_ltv方法如下
def find_customer_id(customer_email)
BwCustomer.find_by(email: customer_email)
end
代碼存在的問題是,當前我遍歷了1000個活動記錄對象,當單擊find_customer_id方法時,它將找到具有給定電子郵件地址的客戶,並且查詢要花15秒鍾以上的時間來處理。
以我的情況,解決此問題的最佳方法是什么?
我有以下解決方案:1.將表連接到,這樣我就不必調用另一個表了。2.延遲加載,僅在需要時加載對象
一些建議將不勝感激
謝謝
您通過電子郵件ID查詢不會花費太多時間。
添加索引在客戶表中的電子郵件列(請參閱本作將通過活動記錄遷移指標- http://apidock.com/rails/v4.2.1/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index )
您的代碼顯示兩次調用find_customer_id
。 這樣做一次,僅觸發1個數據庫查詢
您無需編寫包裝方法Customer.find_by_email(customer_email)
也可以使用
為了進一步優化,您可以在一個循環中收集檢查數據庫中是否存在所需的所有客戶ID,並觸發一個數據庫查詢: Customer.where(email: [list of customer emails])
主要問題是您缺少客戶和調查之間的關聯。 您可以通過加入電子郵件來創建一個
class Survey < ActiveRecord::Base
belongs_to :customer, primary_key: :email, foreign_key: :email
end
但這是一種粗略的方法。 您的應用程序在填寫調查表時是否知道客戶的ID? 還是可以由任何人填寫這些調查,如果有人聲稱與客戶擁有相同的電子郵件,則您可以鏈接嗎?
無論如何,您都需要對兩個電子郵件列都進行索引,並且如果在兩者之間建立了關聯,則可以在控制器代碼中編寫以下內容。
@store = Store.includes(surveys: :customer).find(params[store_id])
這將使數據庫查詢,它渴望加載您將要顯示的所有調查和客戶,以便在循環內可以使用survey.customer
而不為每一行調用新查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.