我使用Angularjs作为前端, 我可以上传图像和一些参数。 我正在使用此指令angular-file-upload来上传带有参数的单个图像:
uploader = $scope.uploader = new FileUploader(
url: '/recipes',
alias: 'cover',
removeAfterUpload: true,
#transformRequest: angular.identity,
headers: {'X-CSRF-TOKEN': csrf_token,'accept': 'application/json'},
withCredentials: true
)
uploader.onBeforeUploadItem = (item)->
#data = angular.toJSON($scope.recipe)
item.formData.push("recipe": angular.toJson($scope.recipe))
#item.upload()
console.info('uploader', $scope.uploader);
uploader.uploadAll()
这是创建操作:
def create
params[:recipe] = JSON.parse params[:recipe]
params[:recipe][:cover] = params[:cover]
@ingredients = Ingredient.where(:id => params[:recipe][:ingredients].map {|ingredient| ingredient[:id]})
@recipe = current_user.recipes.new(params.require(:recipe).permit(:name,:instructions))
@recipe.ingredients << @ingredients
@recipe.user_id = current_user.id
@recipe.save
render 'show', status: 201
end
食谱模型:
class Recipe < ActiveRecord::Base
mount_uploader :cover, AvatarUploader
belongs_to :user
has_and_belongs_to_many :ingredients,:join_table => "ingredients_recipes"
accepts_nested_attributes_for :ingredients
attr_accessor :cover
end
这是请求:
-----------------------------100101598926016265538511946
Content-Disposition: form-data; name="recipe"
{"name":"amzpld","instructions":"mpzmdpzmez","ingredients":[{"id":3,"title":"oeuf"}]}
-----------------------------100101598926016265538511946
Content-Disposition: form-data; name="cover"; filename="10.jpg"
Content-Type: image/jpeg
ÿØÿà�JFIF������ÿÛ�� ( %"1"%),...383,7(-.+
0& $,,,2,,,,,,4,4,,,,,,,,,-,,,,,,,,,,,4,,,,,,,,,,,,,,,ÿÀ��¨,"�ÿÄ�������������
�ÿÄ�@�����!1AQa"q2¡±#BRÁáð3bÑr$ñCT¢ÿÄ��������������
ÿÄ�0�������!1A"Qaq¡2±#B3CÑáðÿÚ���?�öá]®Qâ1 Bs(À¡V_D$¯8þ&¡i6¨Û)Ò
´oóçÊ�dÌôªçñEÏêÚÙ]ëãzn£hÓÚêÄ6I½&&·¼ßËðȨ̈)L¤hGQÞ°Pf�MÔúSkÔBønàôÕjal3YðäKÇÖ¾Á¢@..........
保存配方,但封面=零 我错过了什么
答案 0 :(得分:0)
您正在制作:cover
哈希的params[:recipe]
部分:
params[:recipe][:cover] = params[:cover]
但是你不是白名单,所以不是:
@recipe = current_user.recipes.new(params.require(:recipe).permit(:name,:instructions))
试试这个:
@recipe = current_user.recipes.new(params.require(:recipe).permit(:name, :instructions, :cover))
您的Recipe
模型中还有另一个问题,您正在使用:
attr_accessor :cover
删除该行,您不需要它,因为cover
应该是recipes
表中的真实列,并且如果该列已经存在,这将覆盖将值分配给该列,从而导致您的列包含nil
。
现在,如果您的recipes
表中没有该列,只需在控制台类型中使用迁移添加该列:
rails g migration add_cover_to_recipes cover:string
然后迁移:
rake db:migrate
希望能解决您的问题。