Rails api用回形针

我有简单的回形针模型的rails api:

def create @photo = Photo.new(photo_params) if @photo.save render json: @photo, status: :created, location: @photo else render json: @photo.errors, status: :unprocessable_entity end end private def photo_params params.require(:photo).permit(:image, :title) end 

我的前端框架发送得像这样

 {"title"=>"simpletitletext", "photo"=>{"image"=>......}} 

但它错了,因为rails等待跟随

 {"photo"=>{"title"=>"simpletitle", "image"=>#...}} 

在写完之前,我一直在尝试以不同的方式修复角度数小时。 也许它能够修复铁轨

如果您的服务器有一个如下所示的传入请求:

 {"title"=>"simpletitletext", "photo"=>{"image"=>......}} 

你可以看起来像这样:

 {"photo"=>{"title"=>"simpletitle", "image"=>#...}} 

两者之间的唯一区别是,在第一个中, title键位于photo嵌套哈希之外。 但你希望它在里面。

所以在你的Rails控制器中。 你可以写:

 def photo_params hash = params[:photo] hash.merge(title: params[:title]) end