【问题标题】:setting primary key for a database not named ":id"为未命名为“:id”的数据库设置主键
【发布时间】:2012-04-03 03:18:15
【问题描述】:

我正在使用: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 =&gt; 10) 时收到此错误:

PosController#index 中的参数错误 参数数量错误(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

【问题讨论】:

  • 请注意:“ProductCode”不是惯用的 Rails 列名。应该是product_code
  • 但它是我数据库中的列名。我也应该将其重命名为“product_code”吗?
  • 嗯,是的,我愿意。它不影响性能。但这可能会在某个地方给您带来麻烦,因为 Rails 宣扬“约定优于配置”并假设了很多事情。其中一件事是数据库名称在snake_case中。
  • 仍然没有解决argumentError :(
  • 是的,这就是为什么它是一个提示,而不是一个答案:)

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


【解决方案1】:

设置主键列的名称。

self.primary_key = "product_code"

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 2016-11-21
      • 2011-10-24
      • 2022-01-14
      • 2012-07-03
      • 2014-08-16
      相关资源
      最近更新 更多