我正在尝试实现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
这是用于将强参数列入白名单的 Controller 的片段:
def article_params
params.require(:article).permit(schedules_attributes: [ :id, :schedule_for, :content, :time_zone, :date, :time ])
end
这是我通过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
它选择了正确的时间表,但没有执行更新查询,也没有任何错误。我在这里想念什么吗?
编辑:
我正在使用Ruby 2.0和Rails 4。
最佳答案
以下是一些适合您的想法:
def article_params
schedules_attributes: [ :id, :schedule_for, :content, :time_zone, :date, :time ]
end
应该:
def article_params
params.require(:article).permit(schedules_attributes: [ :id, :schedule_for, :content, :time_zone, :date, :time ])
end
关于ruby-on-rails - Rails-更新nested_attributes不适用于一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19586129/