强参数和嵌套属性

时间:2014-09-27 13:28:31

标签: ruby-on-rails ruby ruby-on-rails-4

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

Event有很多Occurrences。当我提交表单以创建新的Event和一个或多个Occurrences时,我得到了错误,禁止此类被保存:出现的次数不能为空。 #34;但是,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

为什么没有正确传递出现事件的信息?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

也许您需要确保您的表单有multipart: true

相关问题