Reputation:
Error I get: undefined variable article_id
.
What I am trying to achieve : Define the correct route in AJAX and Rails.
What I need: The structure articles/1/comments/2
.
Goal: Note that my goal is to only load comment
using AJAX, not article
.
In the AJAX script below what I currently have undefined is article_id
, for which I wrote the following:
var getArticle = function () {
return $('.article-title').each(function() {
var article_id = $(this).data('article-id');
});
};
$(document).ready(getArticle);
AJAX:
var loadComment = function() {
return $('.comment-content').each(function() {
var comment_id = $(this).data('comment-id');
return $.ajax({
url: "/articles/" + article_id + "/comments/" + comment_id,
type: 'GET',
dataType: 'script',
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
$(document).ready(loadComment);
$(document).on('page:change', loadComment);
Index:
- @articles.each do |article|
%article-title{ :class => "article-title", "data-article-id" => article.id }= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-#{comment.id}" }
Upvotes: 0
Views: 48
Reputation: 6122
Add this to your routes.rb
resources :articles do
resources :comments
end
And add the following controller:
class CommentsController < ApplicationController
def show
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
render json: @comment
end
end
Running something like:
curl http://localhost:3000/articles/123/comments/456.json
will set the params[:article_id]
to 123
and the params[:id]
to 456
, the id
is intended to be used as a comment id.
Upvotes: 2