我有以下錯誤:我可以根據虛擬屬性來計算嗎?
no such column: company_name: SELECT count("contact_emails".id) AS count_id FROM "contact_emails"
模型ContactEmail沒有列COMPANY_NAME。我將它創建爲一個虛擬屬性。
不可能根據這些信息做選擇嗎?那麼我該怎麼做呢?
ContactEmail belongs_to聯繫人belongs_to公司。
我有以下錯誤:我可以根據虛擬屬性來計算嗎?
no such column: company_name: SELECT count("contact_emails".id) AS count_id FROM "contact_emails"
模型ContactEmail沒有列COMPANY_NAME。我將它創建爲一個虛擬屬性。
不可能根據這些信息做選擇嗎?那麼我該怎麼做呢?
ContactEmail belongs_to聯繫人belongs_to公司。
添加到類定義但在數據庫中不存在的虛擬屬性不能用於數據庫選擇,因爲虛擬屬性不在數據庫中。
您可以使用數據庫選擇所需行的超集,然後在將使用虛擬屬性的Rails級別上進行第二次選擇。
如
# model Citizen class file
# model fields:
# id
# name
# age
# city
def can_vote? # a virtual attribute
age >= 18
end
def self.find_voters_by_city(city) # class level finder
# returns array of voters in a city
citizens = Citizen.find_by_city(city) # First select done in database
citizens.select{|citizen| citizen.can_vote?} # Second select is done at Rails
# level using the Array#select
# method
end
注意的是,雖然上述工作正常,你應該非常小心,在性能方面的問題。在Rails級別選擇比在dbms中選擇要慢得多。此外,您通過Rails/DBMS連接傳輸的數據遠多於其他方式需要的數據。
如果您打算定期選擇某些東西,那麼將虛擬屬性推入數據庫通常會更好 - 使其成爲數據庫中的真正屬性。
如果您的表格無法更改,您還可以使用has_one關係創建第二個表格。第二個表格將保存附加屬性。
新增:使用兩個表
### model Contact
# id
# name
# city
has_one :company
def company_name; company.name; end # a virtual attribute
### model Company
# id
# contact_id
# name
# employee_count
belongs_to :contact
### Selecting on city (from Contact) and employee_count (from Company)
city = xyz # the city we are searching for
employee_count = 123 # minimum company size we want
contacts = Contact.find(:all,
:conditions => ["contacts.city = ? and companies.employee_count >= ?",
city, employee_count],
:include => :company)
# above statement does the join and select in the database
# There are also techniques involving named scopes for the above
# And in Rails 3, it will be different too.
我明白了...呃,我想我已經把它設置在公司是一個單獨的表格,並且每個聯繫人都有一個公司。然後我創建了一個虛擬屬性來訪問它。那我該如何查詢呢?謝謝! – Angela 2010-08-19 00:48:04
您可以選擇兩個級別。或者(更快),請使用Rails在數據庫中選擇爲您進行連接。查看答案的添加部分。 – 2010-08-19 04:18:11
順便說一句,通常聯繫人將belongs_to:公司和公司將has_many:聯繫人。你可能想再看看你的模式。或者,可能我沒有全面瞭解您的應用。這很好。 – 2010-08-19 04:32:01
請張貼在生成該錯誤代碼選擇在數據庫中。錯誤是全部粘貼的,還是您編輯的?缺少company_name在您提供的查詢的上下文中沒有太多意義。 – jdl 2010-08-18 03:47:50