2010-08-17 48 views
0

我有以下错误:我可以根据虚拟属性来计算吗?

no such column: company_name: SELECT count("contact_emails".id) AS count_id FROM "contact_emails" 

模型ContactEmail没有列COMPANY_NAME。我将它创建为一个虚拟属性。

不可能根据这些信息做选择吗?那么我该怎么做呢?

ContactEmail belongs_to联系人belongs_to公司。

+0

请张贴在生成该错误代码选择在数据库中。错误是全部粘贴的,还是您编辑的?缺少company_name在您提供的查询的上下文中没有太多意义。 – jdl 2010-08-18 03:47:50

回答

0

添加到类定义但在数据库中不存在的虚拟属性不能用于数据库选择,因为虚拟属性不在数据库中。

您可以使用数据库选择所需行的超集,然后在将使用虚拟属性的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. 
+0

我明白了...呃,我想我已经把它设置在公司是一个单独的表格,并且每个联系人都有一个公司。然后我创建了一个虚拟属性来访问它。那我该如何查询呢?谢谢! – Angela 2010-08-19 00:48:04

+0

您可以选择两个级别。或者(更快),请使用Rails在数据库中选择为您进行连接。查看答案的添加部分。 – 2010-08-19 04:18:11

+0

顺便说一句,通常联系人将belongs_to:公司和公司将has_many:联系人。你可能想再看看你的模式。或者,可能我没有全面了解您的应用。这很好。 – 2010-08-19 04:32:01