gpt4 book ai didi

ruby-on-rails - 强参数和嵌套属性

转载 作者:太空宇宙 更新时间:2023-11-03 18:16:03 25 4
gpt4 key购买 nike

我正在从 Rails 3 升级到 Rails 4,因此我采用了强大的参数。似乎嵌套属性没有被成功传递。我已经阅读了几个相关的 SO 问题和博客文章,但我仍然感到困惑。

Event 有很多Occurrences。当我提交表单以创建新的 Event 和一个或多个 Occurrences 时,我收到“1 个错误禁止保存此类:Occurrences 开始不能为空。 “然而,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"}

这里是模型和 Controller 的相关部分。

应用/模型/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 的信息?

最佳答案

我不确定,但我认为强参数要求您允许关联模型上的外键。那么,也许您的 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

关于ruby-on-rails - 强参数和嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com