环境:
ruby 1.9.3 rails 3.2.8 rails_admin 0.0.5
关系:
class Question < ActiveRecord::Base has_many :comments end
class Comment < ActiveRecord::Base belongs_to :question end
在rails_admin
中更新有Comment
的Question
时出现以下错误:
ActiveRecord::AssociationTypeMismatch (Comment(#70171889588300) expected, got NilClass(#70171855412360))
罪魁祸首 (重写 model 的 id 方法):
def id self[:id].to_s end
ActiveRecord 中:
module ActiveRecord module Associations ...... def ids_writer(ids) pk_column = reflection.primary_key_column ids = Array.wrap(ids).reject { |id| id.blank? } ids.map! { |i| pk_column.type_cast(i) } replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids)) end ...... end end
千万不要偷懒直接重写 model 的 id 方法