Domanda

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
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top