强参数和嵌套属性
问题描述:
我从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"}
下面是模型和控制器的相关章节。
应用程序/模型/ 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? }
应用程序/模型/ occurrence.rb:
class Occurrence < ActiveRecord::Base
belongs_to :event
validates_presence_of :start
应用程序/控制器/ 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_attributes中缺少event_id
?
甚至还没有接近100%肯定,但是这可能是它:
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, :event_id])
end
答
也许你需要确保你的窗体有multipart: true