我一直在努力解决这个问题好几天。我一直收到错误:
ActiveRecord::AssociationTypeMismatch in SatellitesController#create
Satellite(#70098878574220) expected, got String(#70098849353340)
我看过这个网站,但似乎没有任何帮助。这是我到目前为止在我的代码中所拥有的:
在我的new.html.erb文件中:
<%= form_for( @satellite ) do |f| %>
<div class="field">
<%= f.label :parent_id %></br>
<%= f.select( :parent_id, Satellite.all.collect { |s| [ s.name, s.id ] }, { :include_blank => '-select-' } ) %>
</div>
这就是我正在使用的关联:
class Satellite < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
has_many :satellites, class_name: 'Satellite', foreign_key: 'parent_id'
belongs_to :parent_id, class_name: 'Satellite', foreign_key: 'parent_id'
end
任何帮助都会非常感激!
答案 0 :(得分:0)
不确定是否与使用select而不是collection_select有关?
<%= f.select( :parent_id, Satellite.all.collect { |s| [ s.name, s.id ] }, { :include_blank => '-select-' } ) %>
可能是
<%= f.collection_select :parent_id, Satellite.all, :id, :name, { :include_blank => true } %>
看起来在模型的自引用部分中对父级的引用可能是错误的。
belongs_to :parent_id, class_name: 'Satellite', foreign_key: 'parent_id'
我认为这应该是
belongs_to :satellites, class_name: 'Satellite', foreign_key: 'parent_id'