ActiveRecord :: StatementInvalid:Mysql :: Error:'field list'ruby fixture中的未知列'user_id'

时间:2015-03-15 18:08:40

标签: mysql ruby-on-rails ruby-on-rails-4 activerecord fixtures

我尝试运行测试但是失败如下。

[user1 project]$  rake test
DEPRECATION WARNING: String based terminators are deprecated, please use a lambda. (called from included at /home/.gem/ruby/2.1.3/bundler/gems/authlogic-09163c7d2a9b/lib/authlogic/session/callbacks.rb:66)
DEPRECATION WARNING: String based terminators are deprecated, please use a lambda. (called from included at /home/.gem/ruby/2.1.3/bundler/gems/authlogic-09163c7d2a9b/lib/authlogic/session/callbacks.rb:67)
Started

ERROR["test_login_and_access_bookmarks/managing_bookmarks", BookmarksTest, 0.120519093]
 test_login_and_access_bookmarks/managing_bookmarks#BookmarksTest (0.12s)
ActiveRecord::StatementInvalid:         ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'user_id' in 'field list': INSERT INTO `roles` (`id`, `user_id`, `created_at`, `updated_at`) VALUES (4, 2, '2015-03-15 17:54:24', '2015-03-15 17:54:24')


  1/1: [=========================================================================================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.12271s
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
[user1 project]$  

我有两个表用户和角色以及两个名为users.ymlroles.yml的灯具。

users.yml的内容:

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html


user2:
  name: user2
  id: 2

roles.yml的内容:

user2_1:
  id: 4
  user_id: 2

这可能是什么问题?我试图将users表与建立关系的角色链接起来 - 来自users表的user2在角色表中具有角色id 4。非常感谢任何帮助/建议。谢谢!

我查了一些像这样的stackoverflow帖子 - ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column,但没有找到合适的答案。

角色表的结构:

mysql> describe roles
    -> ;
+-----------------+--------------
| Field           | Type         
+-----------------+--------------
| id              | int(11)      
| name            | varchar(255) 
| parent_id       | int(11)      
| description     | varchar(255) 
| default_page_id | int(11)      
| cache           | text         
| created_at      | datetime     
| updated_at      | datetime     
+-----------------+--------------

1 个答案:

答案 0 :(得分:2)

user_id表中没有roles字段;您最有可能尝试在此处指定parent_id

在灯具中实现用户和角色之间关联的最佳方式如下:

# users.yml
user2:
  name: User 2

# roles.yml
role2:
  name: Second role
  parent: user2 (User)

注意:在parent: user2 (User)中设置roles.yml会使role2对象使用user2作为父对象,因为对象类型不同(parent vs { {1}}),应包含user字符串以表示多态关系。

请仔细阅读http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html页面以熟悉灯具。