Excessive use of CPU

Hello guys and girls, I have a problem with a method (new), it is
using 100% of CPU for 15/20 seconds. Follow the method below:

http://pastie.org/537568

kits_controller.rb

def new
@page_title = ‘Add a Kit’
@kit = Kit.new

@num_itens = 16
@kit_inclusions = Array.new
@num_itens.times { @kit_inclusions.push(KitInclusion.new) }

render :action => 'form'

end

def new_do
kit = Kit.new(params[:form])

if kit.save
params[:kit_inclusions].each do |ki|
next if ki[:product_id].empty?

  kit_inclusion = KitInclusion.new(ki)
  kit_inclusion.kit_id = kit.id
  kit_inclusion.save
end

flash[:notice] = 'Kit added!'
redirect_to :action => 'index'

else
flash[:notice] = kit.errors.full_messages.map {|fm| “

  • #{fm}</
    li>”}
    redirect_to :action => ‘new’
    end
    end

    form.hmtl.erb

    <% form_for :form, @kit, :url => { :action => action_do } do |f| -%>
    <% @num_itens.times do |t| -%>
    <% fields_for “kit_inclusions[]”, @kit_inclusions[t] do |i| -%>

  • Product <%= t + 1 %>:<%=
    i.collection_select “product_id”, Product.all(:conditions =>
    {:available => true}, :order => “category_id, model
    ASC”), :id, :display_for_select, {:include_blank => ‘Select…’},
    {:onchange => “qntDefault(‘quantity_#{t}’);”} %><%= i.text_field
    “quantity”, {:onkeydown => “return noLetters(event);”, :class =>
    ‘quantity’, :id => “quantity_#{t}”} %>

  • <% end -%>
    <% end -%>
    <%= image_submit_tag ‘btn_save.png’ %>
    <%= f.hidden_field :id %>
    <% end -%>

    Can you give more information on your environment? It shouldn’t be
    taking that long…

    I’d also advise you to read more documentation; some parts of your
    code are working against the Rails default conventions (for instance:
    the action that creates records is typically ‘create’, not ‘new_do’).
    It’s a small thing, but it means that you have to do extra typing
    (example: the :url option to form_for).

    You may also, if you’re on 2.3, want to look into the nested model
    support stuff, which will handle much of what you’re doing here.

    –Matt J.

    Hello Matt, thanks for the atention.

    I’m under Ruby 1.8.6 and Rails 2.3.2. The machine is a Macbook Pro
    with a Core 2 Duo 2.4GHz and 4GB of RAM. I have declared the nested
    conditions in the model as seen bellow.

    class Kit < ActiveRecord::Base

    has_many :kit_inclusions
    has_many :products, :through => :kit_inclusions

    accepts_nested_attributes_for :kit_inclusions, :allow_destroy =>
    true

    def before_validation
    self.name = self.name.to_s.strip.downcase.titleize
    self.comments = self.comments.to_s.strip.capitalize
    end

    validates_presence_of :name, :message => ‘é requerido’

    def to_s
    self.name
    end

    end

    This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

    | Privacy Policy | Terms of Service | Remote Ruby Jobs