我在网上尝试教程时收到错误'错误的参数数量(2 for 1)'。我是Rails的新手,只是想通过指南。
我的控制器是:
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
end
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
我的数据库代码是:
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.text :text
t.timestamps null: false
end
end
end
给出的参数是:
{"utf8"=>"✓", "authenticity_token"=>"JfpQBSnxU8O839o5YjbZV11TMAWTPgaok1/skSEoGlchdGCulmJuGxFdyj7lUK6WIfrLddCZAaWxOkxRaNqlTA==",
"article"=>{"title"=>"hello world",
"text"=>"hello olivia"},
"commit"=>"Save Article"}
非常感谢任何帮助:)
答案 0 :(得分:0)
如果您尝试此代码,它会在控制台中打印任何错误吗?
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
end
def new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to article_path(@article)
else
logger.warn(@article.errors)
render "new"
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
答案 1 :(得分:0)
问题很可能是因为你没有在if块中调用@ article.save。你正在调用@ article.save然后调用重定向。尝试使用:
if @article.save
redirect_to @article
else
render :new
end