【问题标题】:Keep getting ActiveRecord::AssociationTypeMismatch不断收到 ActiveRecord::AssociationTypeMismatch
【发布时间】:2013-03-17 03:46:38
【问题描述】:

我这几天一直在努力解决这个问题。我不断收到错误:

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

任何帮助将不胜感激!

【问题讨论】:

  • 显示实际错误的堆栈跟踪以及它在您的问题中引用的代码行。
  • 是的,特别是您的create 方法在您的SatellitesController
  • def create @satellite = Satellite.new(params[:satellite]) if @satellite.save redirect_to @satellite,注意:“卫星已成功创建。”否则渲染动作:“新”结束结束

标签: ruby-on-rails forms select


【解决方案1】:

不确定是否与为什么使用 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'

【讨论】:

  • 不,这也没有帮助。我仍然得到相同的 Satellite(...) 预期,得到 String(...)。
  • 当我将其更改为 :parent 我得到错误无效方法 :parent
  • 我需要在关联所在的 Satellite 模型中有一个 Parent 类吗?
  • 你认为你可以为 Satellites 设置你的 schema.rb 部分吗?
  • ActiveRecord::Schema.define(:version => 20130312022717) do create_table "satellites", :force => true do |t| t.string "name" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
相关资源
最近更新 更多