setting primary key for a database not named “:id”

强颜欢笑 提交于 2019-12-01 04:21:45

问题


I am using: rails 2.3.5 ruby 1.8.7 and Windows 7 Home Basic

I was given a database and I connected it to rails, having no problems reading and getting data from it. Now what I want to do is add some functionality in it (add, edit and delete) but when I try to set my primary key to the table's primary key (ProductCode) by doing this code:

class Product < ActiveRecord::Base
self.primary_key :ProductCode
end

I got this error when doing a @products = Product.find(:all, :limit => 10):

ArgumentError in PosController#index wrong number of arguments (1 for 0)

How can I solve this ?

Here's my controller's code:

    class PosController < ApplicationController

    def index
        @cards = Card.find(:all)
        @products = Product.find(:all, :limit => 10)
    end

    def new
        @pro = Product.new
    end

    def edit
    @pro = Product.find(params[:id])
    end

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

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

    def create
    @pro = Product.new(params[:product])

    respond_to do |format|
      if @pro.save
        flash[:notice] = 'product was successfully created.'
        format.html {redirect_to (:controller => "pos", :action => "index")}
        #format.xml  { render :xml => @product, :status => :created, :location => @product }
      else
        format.html { render :controller => "pos",:action => "new" }
        #format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @pro = Product.find(params[:id])
    @pro.destroy

    respond_to do |format|
    flash[:notice] = 'product was successfully deleted.'
      format.html { redirect_to(:controller => "pos", :action => "index") }
      format.xml  { head :ok }
    end
  end
end

回答1:


Sets the name of the primary key column.

self.primary_key = "product_code"




回答2:


self.primary_key returns what rails currently thinks is the primary key and hence takes no arguments. If you want to set the primary key, use self.primary_key = 'blah'.

Earlier versions of rails also supported set_primary_key 'blah', but this was deprecated in rails 3.2.



来源:https://stackoverflow.com/questions/9986658/setting-primary-key-for-a-database-not-named-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!