Ruby on rails 带回形针的Rails api
我有带有简单回形针模型的rails api:Ruby on rails 带回形针的Rails api,ruby-on-rails,angularjs,ruby,Ruby On Rails,Angularjs,Ruby,我有带有简单回形针模型的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 par
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"=>#...}}
在我写这篇文章之前,我已经尝试了好几个小时不同的方法来修复angular。如果您的服务器有一个如下所示的传入请求,它可能能够在rails中修复:
{"title"=>"simpletitletext", "photo"=>{"image"=>......}}
{"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
非常感谢。我写了:Photo.new(title:params[:title],image:params[:Photo][:image]),它也很好用。