我是 Rails 新手
我的目的是将通过 AJAX POST 从 Javascript 接收到的 song_id
和 title
插入数据库(MySQL)
在我的 javascript 文件中
var song_id = "23f4";
var title = "test";
$( document ).ready( function() {
jQuery.ajax({
url: 'create',
data: "song_id=" + song_id + "&title=" + title,
type: "POST",
success: function(data) {
alert("Successful");
},
failure: function() {
alert("Unsuccessful");
}
});
} );
在我的 editor_controller.rb 中
class EditorController < ApplicationController
def new
@song = Song.new
end
def create
logger.debug("#{params[:song_id]}")
logger.debug("#{params[:title]}")
@song = Song.new(song_params)
if @song.save
redirect_to root_path
else
flash[:notice_song_failed] = true
redirect_to root_path
end
end
private
def song_params
params.require(:song).permit(:song_id, :title)
end
问题是当我使用此代码运行 Rails 应用程序时,控制台注意到我
ActionController::ParameterMissing at /editor/create
param is missing or the value is empty: song
我正在尝试使用
private
def song_params
params.require(:song).permit(params[:song_id], params[:title])
end
但它不起作用并注意到我同样的情况,而且在终端日志中告诉我如下
Started POST "/editor/create" for ::1 at 2015-04-01 01:07:23 +0700
Processing by EditorController#create as /
Parameters: {"song_id"=>"23f4", "title"=>"test"}
23f4
test
Completed 400 Bad Request in 1ms
我是否遗漏了代码中的某些内容,谢谢您的帮助。
最佳答案
您根本没有发送歌曲参数。看起来您需要更新 jQuery.ajax 调用中的数据行以包含歌曲参数,如下所示:
data: {song: {song_id: song_id, title: title}}
关于javascript - 使用 AJAX POST 从 javascript 到具有强参数的 Rails 4 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375540/