我有一个控制器'news_controller.rb'用于与数据库连接。当我尝试创建数据库行项目(我通过自动脚本发出请求)时,我收到以下错误
ActionController::ParameterMissing (param is missing or the value is empty: news): app/controllers/api/news_controller.rb:57:in `news_params'app/controllers/api/news_controller.rb:28:in `create'
当我在创建操作中使用params [:category],params [:headline]等时,它可以正常工作。有什么可能的原因和解决方案?
这是我的控制器代码:
module Api
class NewsController < Api::ApiController
respond_to :json
def index
@news = News.all
respond_with :news => @news
end
def show
@news = News.find(params[:id])
respond_with :news => @news
end
def new
@news = News.new
respond_with :news => @news
end
def edit
@news = News.find(params[:id])
respond_with :news => @news
end
def create
if !News.exists?(headline: params[:headline])
#@news = News.new(:category => params[:category], :headline => params[:headline], :content => params[:content], :image_url => params[:image_url])
@news = News.new(news_params)
if @news.save
respond_with :news => @news
else
respond_with @news.errors
end
end
end
def update
@news = News.find(params[:id])
if @news.update(news_params)
respond_with :news => @news
else
respond_with @news.errors
end
end
def destroy
@news = News.find(params[:id])
@news.destroy
respond_to do |format|
format.json { head :no_content }
end
end
private
def news_params
params.require(:news).permit(:category, :headline, :content, :image_url)
end
end
end
答案 0 :(得分:2)
您的params
有值
params = { category: 'value', headline: 'value', .... }
当您使用news_params
时,您希望您的参数格式化为
params = { news: { category: 'value', headline: 'value', .... }}
但事实并非如此。
这就是使用
时的原因@news = News.new(:category => params[:category], :headline => params[:headline], :content => params[:content], :image_url => params[:image_url])
并不适用于
@news = News.new(news_params)
# news_params is nil