2

哪个是最佳实践并给我更好的表现?

例如:

我有包含 5 条记录的状态表,每条记录都需要存储在单独的变量中。

方法1:

@new_status = Status.find_by_status("NEW")
@inprocess_status = Status.find_by_status("InProcess")
@completed_status = Status.find_by_status("Completed")
@occupied_status = Status.find_by_status("Occupied")
@success_status = Status.find_by_status("Success")

方法2:

statuses = Status.all
@new_status = statuses.find {|status| status.status == "NEW"}
@inprocess_status = statuses.find {|status| status.status == "InProcess"}
@completed_status = statuses.find {|status| status.status == "Completed"}
@occupied_status = statuses.find {|status| status.status == "Occupied"}
@success_status = statuses.find {|status| status.status == "Success"}

还是有什么好办法?

4

3 回答 3

2

这将更加高效,因为它只对数据库进行一次查询并且只获取必要数量的数据。这是假设status字段是唯一的。

statuses = Status.where(
  status: ['NEW', 'InProcess', 'Completed', 'Occupied', 'Success']
).order(:status)

@new_status, @completed_status, @inprocess_status, @occupied_status, @success_status = statuses
于 2013-07-06T17:28:45.297 回答
1

You have just 5 records so 5 database queries are going to be very expensive, not at all a good practice.

You can fetch them in memory and assign to instance variables. But I can see a symmetry in Method2 and it looks like very symmetrical code. I strongly suggest not to write symmetrical code in ruby, you can modify it with something like:

Status.all.each{|status| instance_variable_set("@#{status.name.downcase}_status" , status ) }

It will create instance variables and initialise your instance variables with respective statuses.

于 2013-07-06T13:48:27.593 回答
1

如果有 500 万条记录,方法 1 应该更好,因为数据库查询性能更好。

如果只有 5 条记录,方法 2 更好,因为只有一个数据库查询。方法一有5个查询,对于少量的记录来说是非常耗时的。

于 2013-07-06T13:22:49.567 回答