【问题标题】:Got ActiveRecord::AssociationTypeMismatch on model save模型保存时得到 ActiveRecord::AssociationTypeMismatch
【发布时间】:2012-06-08 09:15:51
【问题描述】:

我在使用我的 REST API 保存模型时遇到问题。我有一个包含许多任务和一个客户关联的卡片模型:

class Card < ActiveRecord::Base
  belongs_to :customer

  has_many :card_tasks
  has_many :tasks, :through => :card_tasks

  accepts_nested_attributes_for :tasks
  accepts_nested_attributes_for :card_tasks
  accepts_nested_attributes_for :customer

end


class CardTask < ActiveRecord::Base
  belongs_to :task
  belongs_to :card

  accepts_nested_attributes_for :task
  accepts_nested_attributes_for :card
end

class Task < ActiveRecord::Base
    has_many :cards, :through => :card_tasks
    has_many :card_tasks
end

当我发送这样的 json 时:

{
    "card" = > {
        "miscellaneous" = > "Obervations diverses", 
        "heater" = > "0", 
        "water_quality" = > "", 
        "customer" = > {
          "id" = > "2", "house_name" = > "house_name2", "city" = > "city_2", "lastname" = > "lastname2", "sci" = > "sci2", "postal_code" = > "potal_code_2", "address_line_1" = > "address_line_2", "updated_at" = > "2012-03-05 18:20:57 +0000", "created_at" = > "2012-03-05 18:20:54 +0000", "firstname" = > "firstname2", "address_line_2" = > "address_line_3", "water_used" = > "0"
         },
         "tasks" = > [
          {
            "title" = > "Nettoyage ligne eau", "id" = > "6", "updated_at" = > "2012-02-17 08:40:47 +0000", "created_at" = > "2012-02-17 08:40:47 +0000"
          }, 
          {
            "title" = > "Surveillance", "id" = > "4", "updated_at" = > "2012-02-17 08:40:47 +0000", "created_at" = > "2012-02-17 08:40:47 +0000"
          }
         ]
    }
}

我的创建动作:

  def create
      card = Card.new(params[:card])
      if (card.save)
        respond_with({ :card => card} , :location => nil, status: :created) and return
      end
      respond_with({ :errors => card.errors }, :location => nil, status: :unprocessable_entity)  and return
  end

执行此操作时,我得到了一个:

ActiveRecord::AssociationTypeMismatch (Task(#70249431354580) expected, got ActiveSupport::HashWithIndifferentAccess(#70249421573300)):
  app/controllers/cards_controller.rb:14:in `new'
  app/controllers/cards_controller.rb:14:in `create'

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rest activerecord


    【解决方案1】:

    问题出在 JSON 结构中,Rails 需要 tasks_attributes,而不是 tasks。详情请查看this question

    【讨论】:

    • 谢谢,但现在我在 model.save() 上得到了 ActiveRecord::RecordNotFound(找不到 ID=6 的任务 ID=)
    • 抱歉,没有看到任务是现有记录,而不是新记录。 Guess Accepted_nested_attributes_for 在这种情况下是没用的,它不允许改变关联。您可以尝试修补 nested_attributes.rb、制作猴子补丁或创建自定义处理程序。以下是未实施的更多详细信息:github.com/rails/rails/issues/2925
    • 所以我不能用我的 json 做 Card.new(params[:card]) 相关的任务来创建新卡?
    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    相关资源
    最近更新 更多