我遇到与HABTM关系的情况,必须将shop
和event
模型实例传递给ShopEventsController
才能将事件分配给商店。
路由配置如下:
resources :shops, except: [:create, :destroy] do
resources :events, controller: 'shop_events', only: [:index, :create, :destroy]
什么为我们提供了以下终点:
/shops/:shop_id/events
/shops/:shop_id/events/id
ShopEventsController
具有strong_params的定义如下:
def shop_event_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(params,
only: [
:shop,
:event
])
end
我不知道如何从RSpec请求规范中传递有效参数...
简而言之,我认为我需要:
ActiveModelSerializers::SerializableResource.new(event).to_json
和ActiveModelSerializers::SerializableResource.new(shop).to_json
传递给请求:
let(:event) { create(:unpublished_event, country: country, language: language) }
let(:valid_params) do
{
shop: ActiveModelSerializers::SerializableResource.new(shop),
event: ActiveModelSerializers::SerializableResource.new(event)
}.to_json
end
expect {
post "/shops/#{shop.id}/events", params: valid_params, headers: headers
}.to change(shop.events, :count).by(1)
但是失败了:
ActiveModelSerializers::Adapter::JsonApi::Deserialization::InvalidDocument:
Invalid payload ({:data=>"Expected hash"}): ...
如果我通过在每个模型上添加valid_params
来更改to_json
:
let(:valid_params) do
{
shop: ActiveModelSerializers::SerializableResource.new(shop).to_json,
event: ActiveModelSerializers::SerializableResource.new(event).to_json
}
end
它也不起作用,并因另一个解析错误而失败:
ActionDispatch::Http::Parameters::ParseError:
765: unexpected token at 'shop=%7B%22data%22%3A%7B%2....
以下是创建时发布的内容:
Parameters: {"data"=>{"relationships"=>{"shop"=>{"data"=>{"type"=>"shops", "id"=>"613"}}, "event"=>{"data"=>{"type"=>"events", "id"=>"46"}}}, "type"=>"shop-events"}, "shop_id"=>"613"}
ShopEventsController
具有strong_params的定义如下:
def shop_event_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(params,
only: [
:shop,
:event
])
end
和shop_event_params
仅返回2个ID:
shop_event_params: {:shop_id=>"613", :event_id=>"46"}
这是怎么了?谢谢。