为名为“:id”的数据库设置主键

时间:2012-04-03 03:18:15

标签: ruby-on-rails ruby-on-rails-2

我正在使用:rails 2.3.5 ruby​​ 1.8.7和Windows 7 Home Basic

我得到了一个数据库,我将它连接到rails,没有任何问题从阅读和从中获取数据。现在我想要做的是在其中添加一些功能(添加,编辑和删除),但是当我尝试通过执行以下代码将主键设置为表的主键(ProductCode)时:

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

我在执行@products = Product.find(:all, :limit => 10)时遇到此错误:

PosController#index中的ArgumentError 错误的参数数量(1表示0)

我该如何解决这个问题?

这是我的控制器代码:

    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

2 个答案:

答案 0 :(得分:8)

设置主键列的名称。

self.primary_key =“product_code”

答案 1 :(得分:3)

self.primary_key返回当前认为是主键的rails,因此不带任何参数。如果要设置主键,请使用self.primary_key = 'blah'

早期版本的rails也支持set_primary_key 'blah',但在rails 3.2中已弃用。