【发布时间】:2014-09-27 22:02:34
【问题描述】:
我正在从 Rails 3 升级到 4,因此我采用了强大的参数。似乎嵌套属性没有成功传递。我已经阅读了几个相关的 SO 问题和博客文章,但我仍然感到困惑。
一个Event 有很多Occurrences。当我提交表单以创建新的Event 和一个或多个Occurrences 时,我收到“1 个错误禁止保存此类:出现开始不能为空白。”但是,start 不是空白,正如我通过查看发布的参数确认的那样:
{"utf8"=>"✓",
"authenticity_token"=>"aPRLtUbjW7EMxO2kWSzCEctHYZgvBvwuk2QUymfiwkM=",
"event"=>{"name"=>"some name",
"photo"=>#<ActionDispatch::Http::UploadedFile:0x007f9e9bc95310 @tempfile=# <File:/var/folders/rz/1p7tmbmj2t5fbfv2wjhvwcsh0000gn/T/RackMultipart20140927-52743-10pcxtg>,
@original_filename="10435871_671176211140_3488560836686101357_n.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"event[photo]\"; filename=\"10435871_671176211140_3488560836686101357_n.jpg\"\r\nContent-Type: image/jpeg\r\n">,
"summary"=>"",
"facebook_event_link"=>"",
"occurrences_attributes"=>{"0"=>{"start"=>"09/30/2014",
"_destroy"=>"0"}},
"special"=>"0",
"prose"=>""},
"commit"=>"Create Event"}
这里是模型和控制器的相关部分。
app/models/event.rb:
class Event < ActiveRecord::Base
has_many :occurrences, :dependent => :destroy
accepts_nested_attributes_for :occurrences, allow_destroy: true, reject_if: proc {|o| o[:start].blank? }
app/models/occurrence.rb:
class Occurrence < ActiveRecord::Base
belongs_to :event
validates_presence_of :start
app/controllers/events_controller.rb:
class EventsController < ApplicationController
def new
@event = Event.new
@event.occurrences.build
@event.passes.build
end
def create
@event = Event.create(event_params)
if @event.save
redirect_to @event, notice: 'Event was successfully created.'
else
render :action => "new"
end
end
...
private
def event_params
params.require(:event).permit(
:name, :expiration, :prose, :special, :summary, :photo, :link, :price, :student_price, :registration_switch, :facebook_event_link,
:occurrences_attributes => [:id, :start, :end, :_destroy])
end
end
为什么没有正确传递有关 Occurrences 的信息?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4