As a newcomer to Rails, I am looking to insert song_id
and title
received from JavaScript via AJAX POST into a MySQL database.
In my JavaScript file:
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");
}
});
} );
In my 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
When running the Rails app with this code, the Console informs me of an issue:
ActionController::ParameterMissing at /editor/create
param is missing or the value is empty: song
I tried using:
private
def song_params
params.require(:song).permit(params[:song_id], params[:title])
end
but it produces the same error. Additionally, the terminal log shows:
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
Is there something missing in my code? Thank you in advance.