【问题标题】:Wrong number of Arguments error错误数量的参数错误
【发布时间】:2016-12-20 02:50:54
【问题描述】:

我正在学习教程并使用 Rails 4.2.5 构建一个小型 Instagram 克隆

但我不确定为什么我不断收到此错误数量的参数错误。

编辑:这是文本格式的错误消息,位于第 15 行:

13
14    def update
15        if @pic = Pic.update(pic_params)
16           redirect_to @pic, notice: "Congrats! Your picture was updated!"
17        else
18           render 'edit'
19        end
20    end

我在我的 pics_controller 中定义了一个私有方法“pic_params”,它传入 2 个参数:title 和 :description。

而我的更新动作传入 pic_params 函数:

class PicsController < ApplicationController
before_action :find_pic, only: [:show, :edit, :update, :destroy]

def index
    @pics = Pic.all.order("created_at DESC")
end

def show
end

def edit
end

def update
    if @pic = Pic.update(pic_params)
        redirect_to @pic, notice: "Congrats! Your picture was updated!"
    else
        render 'edit'
    end
end

def new
    @pic = Pic.new
end

def create
    @pic = Pic.new(pic_params)
    if @pic.save
        redirect_to @pic, notice: "Yess! It worked!"
    else
        render 'new'
    end
end


private

def pic_params
    params.require(:pic).permit(:title, :description)
end

def find_pic
   @pic = Pic.find(params[:id])
end

结束

而且我确信我的模型还包括这两个列..(标题和描述)根据我的架构。

ActiveRecord::Schema.define(version: 20161218131012) do

create_table "pics", force: :cascade do |t|
 t.string   "title"
 t.text     "description"
 t.datetime "created_at",  null: false
 t.datetime "updated_at",  null: false

结束

结束

那么为什么我会收到这个错误?应该有根据'pic_params'指定的2个参数!

如果有人可以提供帮助,那就太好了!

【问题讨论】:

  • 如果没有图片参数通过(即您刚刚收到nil),有时会发生这种情况。你能检查你的控制台窗口/日志文件,看看哪些参数实际上被传递给你的控制器吗?
  • 谢谢 Taryn,我刚刚解决了这个问题。 :)
  • 请张贴错误消息,而不是错误消息的图片。我什至无法阅读手机上的错误消息。而且我肯定不能复制和粘贴它。它出现在哪一行?它说什么?
  • 抱歉,我现在已经在错误图片的链接下方写出了错误消息。错误显示“参数数量错误(给定 1,预期为 2)”,它发生在第 15 行。我会注意您对我以后发布的任何帖子的建议。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

Pic.update(pic_params)你错了

Pic 是模型,而不是对象,您只能对对象使用更新。

请尝试:

def update
  if @pic.update(pic_params)
    redirect_to @pic, notice: "Congrats! Your picture was updated!"
  else
    render 'edit'
  end
end

【讨论】:

  • 啊!很棒的收获!谢谢你,杜耶。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2015-06-21
  • 2014-05-28
相关资源
最近更新 更多