Search code examples
ruby-on-railsruby-on-rails-2

Using a database not generated by rake and scaffold in rails


I am using:

Rails 2.3.5
Ruby 1.8.7
Windows 7 Home basic 64-bit

I'm trying to use a database I acquired using mysqldump, and create functions ADD, EDIT, and DELETE to go with it. Now, when I'm creating the edit function, and i'm using its primary key (productCode) as a parameter, i get this error:

ActiveRecord::RecordNotFound in PosController#edit Couldn't find Product without an ID

App Trace: C:/Ruby187/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1567:in find_from_ids' C:/Ruby187/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:616:infind' C:/Users/Aldrin/Documents/Trabaho!/sites/dbSample/app/controllers/pos_controller.rb:13:in `edit'

here's my code:

def edit
@product = Product.find(params[:ProductCode])
end

def update
@product = product.find(params[:ProductCode])
if session[:user_id]
            @log = "Welcome Administrator!"
            @logout="logout"
        else
            @log = "Admin Log in"
            @logout=""
        end

respond_to do |format|
  if @product.update_attributes(params[:product])
    flash[:notice] = 'product was successfully updated.'
    format.html { redirect_to(@product) }
    format.xml  { head :ok }
  else
    format.html { render :action => "edit" }
    format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
  end
end
end

I don't have an :id column in my database.


Solution

  • If productCode is the primary key in the table then you should tell rails to use it instead of id

    class Product << ActiveRecord::Base
    
      self.primary_key = 'productCode'
    
    end
    

    That way standard find calls will work, and you won't need to overwrite methods like to_param as rails will already have done it for you