2015-12-23 155 views
1

我使用Rails的工作,并设置当一些测试中,我遇到过:丢失属性错误

ActiveModel::MissingAttributeError: 
can't write unknown attribute `group_id` 

我猜问题是我的关系。我有

class Group < ActiveRecord::Base 
    has_many :transactions 
    has_many :users 
end 

而且

class Transaction < ActiveRecord::Base 
    belongs_to :group 
    belongs_to :user 
end 

最后,

class User < ActiveRecord::Base 
    belongs_to :group 
    has_many :transactions 
end 

我看到有人因为他们使用has_one,而不是belongs_to,需要添加一个ID列有同样的错误到他们的DB。虽然我使用belongs_to,所以我不认为这是我需要的?有任何想法吗?

回答

1

看起来你没有db中的group_id列。

您必须记住,Rails建立在relational database之上,这意味着您可以通过引用foreign_key来访问“相关”数据。

在设置belongs_to/has_many协会,belongs_to表需要有相应的外键(在你的情况group_id):

enter image description here

你的错误没有说明你是哪个模型接受例外;我会冒险猜测它是UserTransaction

-

要解决它,我会建议建立一个迁移到group_id属性添加到适当的模式:

$ rails g migration AddGroupId 

#db/migrate/add_group_id____________.rb 
class AddGroupID < ActiveRecord::Migration 
    def change 
     add_column :users, :group_id, :integer 
    end 
end 

$ rake db:migrate 
1

除非您创建的模型指的是具有引用的迁移,否则您仍然需要在数据库中进行迁移。一个简单的方法来检查数据库是否有一个是访问您的some_project_root/db/schema.rb。如果你没有看到你想要的领域,那么你将不得不生成一个。你这样做的方式是运行一个rails g migration AddXidToY x_id:integer。它应该为你想要的表中的id设置一个字段。