我正在测试一个使用 mysql 数据库的链接缩短器 Sinatra 应用程序。当我输入要缩短的链接时,我收到了这个 mysql 错误
(mysql_errno=1364, sql_state=HY000) Field 'link_identifier' doesn't have a default value Query: INSERT INTO `urls` (`original`) VALUES ('http://pryrepl.org/screencasts.html')
我假设这意味着字段 link_identifier 应该有一个默认值
urls 和visits 表都有link_identifier 字段,但links 表没有。但是,在创建表的代码中,复制到下面,它是具有“属性:标识符”的 Link 类。有谁知道我将如何解决这个问题?
mysql> show columns from urls;
+-----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| original | varchar(255) | YES | | NULL | |
| link_identifier | varchar(50) | NO | MUL | NULL | |
+-----------------+------------------+------+-----+---------+----------------+
3 rows in set (0.12 sec)
mysql> show columns from visits
-> ;
+-----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| created_at | datetime | YES | | NULL | |
| ip | varchar(39) | YES | | NULL | |
| country | varchar(50) | YES | | NULL | |
| link_identifier | varchar(50) | NO | MUL | NULL | |
+-----------------+------------------+------+-----+---------+----------------+
5 rows in set (0.08 sec)
mysql> show columns from links
-> ;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| identifier | varchar(50) | NO | PRI | NULL | |
| created_at | datetime | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
代码
class Url
include DataMapper::Resource
property :id, Serial
property :original, String, :length => 255
belongs_to :link
end
....
class Link
include DataMapper::Resource
property :identifier, String, :key => true
property :created_at, DateTime
has 1, :url
has n, :visits
...
class Visit
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
property :ip, IPAddress
property :country, String
belongs_to :link
after :create, :set_country
....
更新 - 源代码似乎已经有办法创建一个链接标识符来满足 mysql 的要求,但它似乎没有工作
def self.create_link(original)
url = Url.create(:original => original)
if Link.first(:identifier => url.id.to_s(36)).nil? or !DIRTY_WORDS.include? url.id.to_s(36)
link = Link.new(:identifier => url.id.to_s(36))
link.url = url
link.save
return link
else
create_link(original)
end
end
end