我有一个页面,我可以显示所有客户的详细信息,或者如果在参数中指定,只显示一个客户的详细信息。
我的控制器看起来像这样。
def display_customers @all_customers = Customer.all if params[:customer_id] @customers = Customer.find(:all, conditions: ["id = ?", params[:customer_id]]) else @customers = @all_customers end end我使用@all_customers来填充客户的下拉列表。 我使用@customers来完成每个客户的each循环。 然后,如果指定了customer_id参数,则@customers将只是单个客户。
这很好用,但@customers = Customer.find(...)是一个额外的数据库查询。 我已经拥有@all_customers所有客户,所以我可以更好地从那里获取我需要的一条记录 - 而不是再次回到数据库。
I have a page where I can either display all customers' details, or if specified in the params, just one customer's details.
My controller looks something like this.
def display_customers @all_customers = Customer.all if params[:customer_id] @customers = Customer.find(:all, conditions: ["id = ?", params[:customer_id]]) else @customers = @all_customers end endI use @all_customers to populate a dropdown of customers. I use @customers to perform an each loop through each customer. Then, if the customer_id param is specified, @customers will just be the single customer.
This works just fine but @customers = Customer.find(...) is an extra DB query. I already have all the customers in @all_customers so I though there would be a better way to grab the one record I need from there - instead of going back to the DB again.
最满意答案
你可以使用所有Enumerables内置的find ...
if params[:customer_id] @customer = @all_customers.find { |c| c.id == params[:customer_id] } else #.........但可能不应该。
根据记录的数量,这可能不会更快,因为您的数据库查询将使用索引,其中上述代码使用线性搜索所有返回的记录。 机会是第二个数据库查询是要走的路。
您还应该重写您的查询。 Rails足够聪明,你不必在通过ID查找记录时传递条件; 你找到它。 这些是相同的:
# BAD: @customers = Customer.find(:all, conditions: ["id = ?", params[:customer_id]]) # BETTER: @customers = Customer.find_by_id(params[:customer_id]) # BEST: @customer = Customer.find(params[:customer_id])如果你真的想要它是一个数组,只需将结果包装在[] 。
You can use the find which is built in to all Enumerables...
if params[:customer_id] @customer = @all_customers.find { |c| c.id == params[:customer_id] } else #...... but probably shouldn't.
Depending on the number of records, this may not be any faster, as your database query will use an index, where the above code uses a linear search through all the returned records. Chances are a second database query is the way to go.
You should also rewrite your query. Rails is smart enough that you don't have to pass conditions when finding a record by its ID; you just find it. These are identical:
# BAD: @customers = Customer.find(:all, conditions: ["id = ?", params[:customer_id]]) # BETTER: @customers = Customer.find_by_id(params[:customer_id]) # BEST: @customer = Customer.find(params[:customer_id])If you really want it to be an array, just wrap the result in [].
更多推荐
发布评论