我如何在另一个控制器中创建客人(对我来说是事件)

How i can create Guests in another controller (for me it is Events)

我无法在事件控制器中创建来宾。

来自 rails 的错误:

undefined method `permit' for [{"name"=>"John"}, {"name"=>"Mike"}]:Array

如何从活动控制器中保存来宾,请帮忙。

这是我的事件控制器:

class EventsController < ApplicationController

 def create
    @event = Event.create(event_params)
    @guest = Guest.create(guest_params)

    respond_with [@event, @guest]

  end

private
  def event_params
    params.require(:event).permit(:name, :description, :date)
  end

  def guest_params
    params.require(:guests).permit(:name)
  end
end

所以,这是JSON的观点:

date:"25.07.2016"
description:"Biggest Show"
guests:[{name: "John"}, {name: "Mike"}]
name:"Night Show"

我的classEvent.rb:

class Event < ActiveRecord::Base
  has_many :guests
  def as_json(options = {})
    super(options.merge(include: :guests))
  end
end

我的classGuest.rb:

class Guest < ActiveRecord::Base
  belongs_to :event
  def as_json(options = {})
    super
  end
end

和来宾控制器(如果更有帮助的话):

class GuestsController < ApplicationController
  respond_to :json
  def index
    respond_with Guest.all
  end

  def show
    respond_with Guest.find(params[:id])
  end

  def create
    respond_with Guest.create(guest_params)
  end


  private
  def guest_params
    params.require(:guest).permit(:name)
  end
end

guest_params 方法更改为:

def guest_params
  params.permit(guests: [:name])
end

不能对数组调用 permit

因为 guests 在你看来是一个散列数组 [{name: "John"}, {name: "Mike"}],你应该在你的控制器中做这样的事情:

# app/controllers/events_controller.rb
class EventsController < ApplicationController
  def create
    @event = Event.create(event_params)
    @guests = guests_params[:guests].map { |guest|
      Guest.create(name: guest[:name], event: @event)
    }

    respond_with @event
  end

  private
    def event_params
      params.require(:event).permit(:name, :description, :date)
    end

    def guests_params
      params.require(:event).permit(:guests)
    end
end

或者,您可以将视图更改为 return guests: { name_1: "John", name_2: "Mike", name_3: ... ],然后使用 permit 方法,该方法需要访客的索引:

# app/controllers/events_controller.rb
class EventsController < ApplicationController
  def create
    ...
    @guests = (1..max_index).map { |index|
      Guest.create(guest_params(index).merge({ event: @event }))
    }
    ...
  end

  private
    ...
    def guest_params index
      params.require(:guests).permit("name_#{index}")
    end
end

我没有根据解释器检查代码,但我想你明白了:)

编辑:将 event_params.guests 更改为 params[:event][:guests],因为 guests 不是 event_params 散列的方法或字段。还从 permit 方法中删除了来宾,因为它可能会在创建事件时出错。但我不确定这是否是一个好的实践解决方案,或者它是否完全按照这种方式工作。还是只是出个主意:)