简体   繁体   English

如何查找具有主键的对象是 rails 上的字符串

[英]How to find an Object with primary key is string on rails

I has a table Reading(ID:string(8),title:string(100),contents:text) And in Reading models:我有一个表 Reading(ID:string(8),title:string(100),contents:text) 在 Reading 模型中:

class Reading < ActiveRecord::Base
  self.table_name = "reading"
  self.primary_key = :ID
end

In reading controller在读取控制器

private
    # Use callbacks to share common setup or constraints between actions.
    def set_reading
      @reading = Reading.find(params[:ID])
    end

I have a record of reading table with ID is "20150910".我有一个ID为“20150910”的读表记录。

But Reading.find("20150910") not work.但是Reading.find("20150910")不起作用。

You should look up about uuids - this is supported by default in Rails 4 ; 您应该查找有关uuids的信息——Rails 4 默认支持它 it's essentially the same functionality you're seeking.它本质上与您正在寻找的功能相同。

We do it:我们这样做:

在此处输入图像描述

If you've set the primary_key in your model, and have it set in your db:如果您在模型中设置了primary_key ,并将其设置在您的数据库中:

execute "ALTER TABLE nodes ADD PRIMARY KEY (uuid);"

... you should be able to use the find method with the passed string quite simply: ...您应该能够非常简单地将find方法与传递的字符串一起使用:

 @reading = Reading.find params[:id]

-- --

As stated in the comments, the issue you have could be to do with the parameter you're passing through your routes.如评论中所述,您遇到的问题可能与您通过路线传递的参数有关。 If you're not setting ID explicitly, you'll have to deal with :id :如果您没有明确设置ID ,则必须处理:id

#config/routes.rb
resources :readings, param: "ID"

Rails expects by default for the primary key to be an int called "id" (notice the lower case).默认情况下,Rails 期望主键是一个名为“id”的整数(注意小写)。 You will need to override this default and set a new primary key.您将需要覆盖此默认值并设置新的主键。 Here is a helpful blog post that explains the process better than I can here: http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/这是一篇有用的博客文章,比我在这里更好地解释了这个过程: http ://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/

Edit: I believe the detail you might be missing is that you need to make ID unique and not null in the database.编辑:我相信您可能缺少的细节是您需要在数据库中使 ID 唯一且不为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM