我最近更新了我的ruby版本和rails版本。
ruby 1.9.3 to ruby 2.1.1
rails 3.2.6 to rails 4.0.0
然后安装新的宝石
protected_attributes(1.0.3)
turbolinks(2.5.3)
在运行代码时,我遇到了以下错误,无法创建和更新方法。
.new,.update mehods 错误的参数数量(2 for 1)错误。 例如
**wrong number of arguments (2 for 1)**
def create
**@gallery = Gallery.new(gallery_params)**
respond_to do |format|
if @gallery.save
format.html { redirect_to :back, :notice => t('notice.gallery_created') }
format.json { render json: @gallery, status: :created, location: @gallery }
else
format.html { render action: "new" }
format.json { render json: @gallery.errors, status: :unprocessable_entity }
end
end
end
private
def gallery_params
params.require(:gallery).permit(:title, :user_id, :description, images_attributes: [:title, :description, :image, :user_id])
end
我从表格中发送以下参数。
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4DosQk69bQzV9idZapxjseVPNedORytYtNYH4rUCeBk=", "gallery"=>{"title"=>"test title 10", "description"=>"this is the gallery desription", "user_id"=>"1", "images_attributes"=>{"0"=>{"title"=>"test image", "description"=>"", "image"=>#<ActionDispatch::Http::UploadedFile:0xb48788b8 @tempfile=#<Tempfile:/tmp/RackMultipart20160229-7649-3kw561>, @original_filename="564650_685411374823853_181629729_n.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"gallery[images_attributes][0][image]\"; filename=\"564650_685411374823853_181629729_n.jpg\"\r\nContent-Type: image/jpeg\r\n">, "user_id"=>"1"}}}, "commit"=>"Update", "locale"=>"en"}
它为我的应用程序中的每个表单(form_for或nested_form_for)提供了错误。
尝试使用控制器中的以下代码保存我的数据但.new .update仍有问题。 例如
@gallery = Gallery.new
@gallery.title = "test title 10"
@gallery.description = "this is the gallery description"
@gallery.user_id = 1
@gallery.save
答案 0 :(得分:0)
试试这个:
def gallery_params
params.require(:gallery).permit(:title, :user_id, :description, images_attributes: [:title, :description, :image, :user_id])
end
答案 1 :(得分:0)
一旦尝试这样,让我们看看问题是否在强参数
def create
@gallery = Gallery.new({"title"=>"test title 10", "description"=>"this is the gallery desription", "user_id"=>"1", "images_attributes"=>{"0"=>{"title"=>"test image", "description"=>"", "image"=>#<ActionDispatch::Http::UploadedFile:0xb48788b8 @tempfile=#<Tempfile:/tmp/RackMultipart20160229-7649-3kw561>, @original_filename="564650_685411374823853_181629729_n.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"gallery[images_attributes][0][image]\"; filename=\"564650_685411374823853_181629729_n.jpg\"\r\nContent-Type: image/jpeg\r\n">, "user_id"=>"1"}}})
respond_to do |format|
if @gallery.save
format.html { redirect_to :back, :notice => t('notice.gallery_created') }
format.json { render json: @gallery, status: :created, location: @gallery }
else
format.html { render action: "new" }
format.json { render json: @gallery.errors, status: :unprocessable_entity }
end
end
end