【问题标题】:Rails nested attributes for through model in JSON在 JSON 中通过模型的 Rails 嵌套属性
【发布时间】:2015-07-10 10:42:13
【问题描述】:

我有三个模型。在我的 Rails 应用程序中,它们如下所示(为简洁起见,省略了不必要的代码):

class User < ActiveRecord::Base
  has_many :schedules
  has_many :payouts, :through => :schedules

  accepts_nested_attributes_for :schedules
end

class Schedule < ActiveRecord::Base
  belongs_to :user
  belongs_to :payout
end

class Payout < ActiveRecord::Base
  has_many :schedules
  has_many :users, :through => :schedules
end

这是典型的 Rails 多对多关联与直通模型。但是,在前端,当将 JSON 组合在一起以 POST 到用户的控制器时,我需要包含尚未创建的 user_id。

JSON 看起来像这样:

{
  "user": {
    "schedules_attributes": [{
      "payout_id": 5,
      "user_id": null
    }]
  }
}

上述 JSON 的问题在于 user_id 未设置,因为它正在创建中。这应该怎么做?

【问题讨论】:

  • 这实际上是关于您的控制器中的内容 - 您可以添加 create 代码吗?
  • 在 has_many/belongs_to 关系中,我只是在请求正文中发送一组 JS 对象,例如:当我允许控制器中的嵌套属性时,'Record.new(record_params)` 工作。我不能做同样的事情/这就是它不能正确保存的原因吗?

标签: ruby-on-rails ruby json activerecord


【解决方案1】:

如果你要创建一个新用户和一些相关的时间表,那么你不需要为一个时间表指定 user_id,Rails 会在创建用户记录后自动设置它。这就是 accept_nested_attributes_for 的工作原理。

【讨论】:

  • 那么这个JSON应该设置user_id?
  • 不,不应该(因为没有用户)。 Rails 负责设置 user_id。只需将用户参数与 schedules_attributes 一起传递,它就会明白 schedule 属于 user 并设置 user_id。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
相关资源
最近更新 更多