2013-08-03 74 views
0

单个记录我使用的轨道v3.0.9轨3找到活动记录收集

我无法弄清楚如何在活动记录收集

我试图用什么方法找到我控制台,

@customers = Customer.all  # returns collection of records 

@customer = @customers.find {|customer| customer.id == 1 } # returns the correct record 

现在,我使用的关联集合在同一个find方法

@projects = @customer.projects # returns collection of Project records 

@project = @projects.find {|project| project.id == 1 } # got error 
    ActiveRecord::RecordNotFound: Couldn't find Project with ID=1... 

请任何人解释如何查找方法不同于上述两个例子

有没有其他方式来查找关联集合中的记录?

我用阵列检测,让我的项目记录

@project = @projects.detect {|project| project.id == 1 } # returns the correct record 

哪种方法最好是找到的活动记录阵列单记录?

回答

0

只要做到这一点:

@customer = Customer.find(customer_id) 

例如:

@customer = Customer.find(1) 
# => will return the customer with the id equal to 1 
0

你有几个机会:

# this returns the customer with the id 1 - if a customer with id 1 exists! 
@customer = Customer.find(1) 
@customer = Customer.where(:id => 1).first 

# this returns the project with id 1 and customer_id = @customer.id 
@customer.projects.find(1) 
@customer.projects.where(:id => 1).first 

你的错误简单的方法,那你没有一个项目与ID = 1和CUSTOMER_ID = @ customer.id

要回答你的问题..你应该使用where查询..这是新的轨道3的方式。所有查找方法在导轨4中不推荐使用,并从导轨内核中提取出来,作为额外的宝石。

+0

它的罚款,但Model.find和Model.where子句将执行一个数据库查询,其中作为阵列方法发现和检测将通过迭代(不包括查询)返回一个对象,所以我想Array方法 – nishanthan

+0

你是什么意思?如果您在数据库中保存的对象总是要询问他们,让他们走出你的数据库的:-) .. – Mattherick

+0

假设我们在表(5个记录)已经最低记录,并要保存在单独的变量中的每个对象进一步计算,最好使用Array方法查找并检测ActiveRecord而不是ActiveRecord在哪里查找。例如 http://stackoverflow.com/questions/17503221/rails3-which-is-better-code-for-performance – nishanthan