我正在使用rails 4.0构建一个小例子。当我在2个模型之间创建一对多关系时,有些奇怪。集群has_many:请求和请求belongs_to:cluster。
class Cluster < ActiveRecord::Base
has_many :requests
paginates_per 10
end
class Request < ActiveRecord::Base
paginates_per 10
belongs_to :cluster, :class_name => "Cluster"
end
然后,当我创建一个集群并插入一些请求时,我收到错误
def do_cluster
requests = Request.where(:state => 'new').limit(4)
cluster = Cluster.new()
cluster.state = "new"
requests.each do |request|
cluster.requests << request
puts "abc"
request.state = "clustered"
end
cluster.save
redirect_to "index"
end
=&GT;在16ms内完成500内部服务器错误(ActiveRecord:1.0ms)
ActiveModel :: MissingAttributeError(无法写入未知属性cluster_id
):
app / controllers / admin_controller.rb:21:在`do_cluster&#39;。
我不明白我做错了什么。有人可以帮忙吗?
答案 0 :(得分:3)
您需要知道的问题虽然ActiveRecord
和数据库上的表是通过Rails中的约定连接的,但这并不意味着模型中的Association
将创建一个链接(外键,或者数据库中的偶数列。
在您的情况下,当您创建表cluster_id
'requests'
中需要一个名为'requests'
的列
<强>模型强>
class Cluster < ActiveRecord::Base
has_many :requests
paginates_per 10
end
class Request < ActiveRecord::Base
paginates_per 10
belongs_to :cluster
end
<强>移植强>
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
# any fields
t.integer :cluster_id
t.timestamps
end
end
end