I'm trying to implement an application that works basically like that:
First, the user adds movies information on database (i.e. tittle, language, subtitles). Once added, the user can select some of those movies to make a wish list and publish this list.
So, the first part is done but I'm a little bit stuck on publishing it. I did a post request via AJAX (code bellow), where movieList is the json Object with all the selected movies.
$.ajax({
type: "POST",
url: "/lists",
data: { list: movieList},
success: function(data,status,xhr){
console.log(status);
// alert("SUCCESS!");
},
error: function(xhr,status,error){
console.log(status,error);
alert("ERROR!");
}
However, I'm not quite sure about how to call it on my ListsController, I saw a lot of related questions but to be honest I didn't understand how everything works to put together (it's my first rails app). I've tried this one, which in fact accepts the JSON POST, but I think it creates a list for each of the movies, so if I have n movies, it'll create n lists. What I want is to create a list with all the movies on there (only one list for n movies). Also, if I want to create another list with some of those movies that are already in an added list, using the answer of this link gives me an ActiveRecord::RecordNotUnique (rollback).
Based on that, I was thinking, there's a better way to implement this part? How can I call the JSON on my controller to create objects and access them thereafter? (i.e. on a show route).
EDIT: My JSON file looks like that:
"list":{ "0":{
"tittle":,
"listID":,
"language":,
"subtitles:",
}
"1":{
"tittle":,
"listID":,
"language":,
"subtitles:",
}
}
When I call the POST, it gives me "Unpermitted parameters: 0, 1", which I understand once the parameters in fact doesn't exist on my database table (it's only list_id, tittle, subtitles and language), but I don't know how to recognize those parameters. All I want to do is to create a list on my server using this json file, which is created on front end side when the user clicks a button.
UPDATE:
I changed the AJAX to the following code:
$.ajax({
type: "POST",
url: "/lists",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({ list: movies }),
success: function(data,status,xhr){
console.log(data);
// alert(data);
},
error: function(xhr,status,error){
console.log(status,error);
alert("ERROR!");
}
Now it sends full json object,although I still don't know how to handle on my rails controller, for now I can create a list for each json object, but I want to create a single list for all.
def create
movies = []
movie_params.each do |p|
movie = List.new(p)
movies << movie if movie.save
end
render json: movies, status: 201
end
def movie_params
params.require(:list).map do |p|
ActionController::Parameters.new(p.to_hash).permit( :list_id, :tittle, :language, :subslanguage)
end
end
Content-type: application/jsonand rails will handle for you.