gpt4 book ai didi

ruby-on-rails - 在模型保存时获取 ActiveRecord::AssociationTypeMismatch

转载 作者:行者123 更新时间:2023-12-03 00:52:21 24 4
gpt4 key购买 nike

我在使用 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'

我做错了什么?

最佳答案

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

关于ruby-on-rails - 在模型保存时获取 ActiveRecord::AssociationTypeMismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878930/

24 4 0
文章推荐: ruby-on-rails-3 - 为什么是:notice not showing after redirect in Rails 3
文章推荐: ruby-on-rails - 使用 json 响应时出现 406 错误
文章推荐: java - 比较 Java 时间的最佳方法
文章推荐: ruby-on-rails - 自动刷新
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com