【问题标题】:Sinatra activerecord initializeSinatra 活动记录初始化
【发布时间】:2014-11-11 14:23:31
【问题描述】:

我遇到了一个奇怪的情况。有人能给我建议吗? 我正在用

开发一个应用程序
Ruby1.8.7
Sinatra 1.4.4
Activerecord 3.2.14
Mysql 5.6.19 

我几乎完成了开发,但在最后一刻我得到了堆栈。 我在 MySQL 中有两个表。

CREATE TABLE items(
  id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, 
  type text,
  keyword text,
  postid INT,
  created_at datetime NOT NULL);

CREATE TABLE comments(
  id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
  comment text,
  yourname INT,
  postid INT,
  created_at datetime NOT
  NULL);

在 Sinatra 应用程序中,我声明了类。

class Comment < ActiveRecord::Base end

class Item < ActiveRecord::Base end

出于调试目的,我编写了这段代码并运行。

get "/l" do

  # New comment and set initial value.
  y={:yourname =>"3",:comment =>"commenttest"}

  com = Comment.new(y)
  p com.attribute_names()
  p com

  # New items and set initial value.
  kensaku = {:type=>"000"}
  k = Item.new(kensaku)

  p k.attribute_names()
  p k

  k.type="555"
  p k

end

所以现在我在控制台上发现了非常有趣的东西。 注释类以初始值成功新建。 但是Item类成功了new但是没有设置初始值。 我想知道为什么会这样?

#-- Comment class 
["postid", "id", "comment", "created_at", "yourname"]
#<Comment id: nil, comment: "commenttest", yourname: 3, postid: nil, created_at: nil>

#-- Item class 
["type", "postid", "id", "keyword", "created_at"]
#<Item id: nil, type: nil, keyword: nil, postid: nil, created_at: nil>
#<Item id: nil, type: "555", keyword: nil, postid: nil, created_at: nil>

【问题讨论】:

  • 尝试更改type属性的名称
  • 哦,天哪...非常感谢!

标签: ruby activerecord sinatra


【解决方案1】:

列名type 是 ActiveRecord 中的reserved word

虽然这些列名是可选的,但它们实际上是由 活动记录。 避免使用保留关键字,除非您想要 额外的功能。 例如,type 是保留关键字,用于 使用单表继承 (STI) 指定表。如果你不是 使用 STI,尝试类似的关键字,如“上下文”,它可能仍然 准确描述您正在建模的数据。

【讨论】:

  • 我倾向于同意。但这是由软件(即 ActiveRecord)进行(或不进行)的检查。如果你愿意,你可以打开一个功能请求,也许他们会在未来的版本中添加这个检查