当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - what is better SQL optimization and DRY code?

问题描述:

Which is the best strategy for writing DRY code as well as SQL optimized?

Passing an optional parameter, subject_id, and passing @subject to the view only if this parameter exists as well as filtering "pages" that contain that subject_id in their record.

This:

def list

@pages = Page.order("pages.position ASC")

if (params.has_key?(:subject_id))

@subject = params[:subject_id]

@pages = @pages.where("subject_id = ?", params[:subject_id])

end

end

Or:

def list

if (params.has_key?(:subject_id))

@subject = params[:subject_id]

@pages = Page.order("pages.position ASC").where("subject_id = ?", params[:subject_id])

else

@pages = Page.order("pages.position ASC")

end

end

网友答案:

I'd probably go with a slight variation of the first one:

def list
  @pages = Page.order("pages.position ASC")
  if (params.has_key?(:subject_id))
    @subject = params[:subject_id]
    @pages = @pages.where(:subject_id => params[:subject_id])
  end
end

In either case, @pages won't hit the database until you try to iterate over it so both versions will be the same as far as the database is concerned. Furthermore, these two should be identical (or as close to identical as to not matter) as far as Ruby is concerned:

x = M.order(...).where(...)

# and 
x = M.order(...)
x = x.where(...)

so the above version of list is DRYer and should perform exactly the same as the more repetitive version.

分享给朋友:
您可能感兴趣的文章:
随机阅读: