Rails - 更新nested_attributes不适用于一对多关系

MoM*_*oMo 9 activerecord ruby-on-rails nested-attributes ruby-on-rails-4

我正在尝试实现nested_attributes并创建一个计划正在运行.但它在编辑时失败而没有出现任何错误.它适用于一对一的关系,但不适用于一对多的关系.我正在传递日程表的ID,正如本文档中所述:NestedAttributes

我有这些模型:

class Article < ActiveRecord::Base
  has_many :schedules

  accepts_nested_attributes_for :schedules
end

class Schedule < ActiveRecord::Base
  belongs_to :article
end
Run Code Online (Sandbox Code Playgroud)

这里是控制器的片段,用于将强参数列入白名单:

def article_params
  params.require(:article).permit(schedules_attributes: [ :id, :schedule_for, :content, :time_zone, :date, :time ])
end
Run Code Online (Sandbox Code Playgroud)

这是我通过rails控制台尝试的示例:

article_params = {"schedules_attributes"=>{"0"=>{"schedule_for"=>"pre", "content"=>"This is a scheduled message for ETS - !!!!!!!", "time_zone"=>"American Samoa", "date"=>"2013-10-20", "time"=>"11:15 AM", "id"=>"1"}}}

article = Article.find(1)

article.update(article_params)

D, [2013-10-25T16:42:50.266517 #2296] DEBUG -- :    (0.1ms)  BEGIN
D, [2013-10-25T16:42:50.267789 #2296] DEBUG -- :   Schedule Load (0.3ms)  SELECT "schedules".* FROM "schedules" WHERE "schedules"."article_id" = $1 AND "schedules"."id" IN (1)  [["article_id", 1]]
D, [2013-10-25T16:42:50.273288 #2296] DEBUG -- :    (0.3ms)  COMMIT
Run Code Online (Sandbox Code Playgroud)

它选择了正确的计划,但它没有进行更新查询,也没有任何错误.我在这里错过了什么吗?

编辑:

我正在使用Ruby 2.0和Rails 4.

One*_*ude 0

这里的问题似乎是您没有accepts_nested_attributes_for正确使用强大的参数。

你能试一下吗

模型

accepts_nested_attributes_for :schedules
Run Code Online (Sandbox Code Playgroud)

控制器文件

def article_params
    params.require(:article).permit(:my, :attributes, :schedules: [:schedule, :whitelist])
end

@article.update_attributes!(article_params)
Run Code Online (Sandbox Code Playgroud)

accepts_nested_attributes_for对我来说,rails 需要强大的参数并以这种方式工作是愚蠢的,但也许我错过了一些东西。

还可以尝试使用.update_attributes!a !,这会告诉 Rails 引发错误,这样你就知道发生了什么。

article[schedules_attributes][0][schedule_for]的 for 中,我对此不是 100% 积极,但我相信这将作为 params[:article][:schedules_attributes_0][schedule_for] 发送

你能尝试把article[schedule_attributes][][attribute_name]