在AJAX和Rails中定义路由

时间:2016-03-14 15:58:21

标签: javascript jquery ruby-on-rails ajax

我得到错误:undefined variable article_id

我想要实现的目标:在AJAX和Rails中定义正确的路由。

我需要什么:结构articles/1/comments/2

目标:请注意,我的目标是仅使用AJAX加载comment,而不是article

在下面的AJAX脚本中,我目前拥有的 undefined article_id,我为此写了以下内容:

  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);

指数:

  - @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}" }

1 个答案:

答案 0 :(得分:2)

将此添加到您的library(dplyr) library(tidyr) data_frame(myString) %>% separate(myString, into = c("V1", "V2", "V3"), extra = "merge") # Source: local data frame [3 x 3] # # V1 V2 V3 # (chr) (chr) (chr) # 1 frank 1 103; his name is frank # 2 alice 2 09; sometimes; she says hi # 3 kim 3 123; bla;bla;bla;

routes.rb

并添加以下控制器:

resources :articles do
  resources :comments
end

运行类似:

class CommentsController < ApplicationController
  def show
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    render json: @comment
  end
end

会将curl http://localhost:3000/articles/123/comments/456.json 设置为params[:article_id],将123设置为params[:id]456旨在用作评论ID。