将ajax发送到rails中的控制器

时间:2016-01-10 10:29:35

标签: ruby-on-rails ajax

我是rails的新手,我遇到了向控制器发送ajax的问题​​:

有一个html的link_to:

<%= link_to "回复", {:controller=>"activites", :action=>"add_in_comment"},...%>

当我点击它时,我将ajax发送到&#34; add_in_comment&#34;的控制器动作。提出要求。

$(".each_comment .comment").on("click",function() {
    var post_data = {
        comment_to_id:$(this).attr("data-test1"),
        content:$(this).siblings("input").val(),
        comment_from_id:$(this).attr("data-cur_u"),
        activity_id:$(this).attr("data-activity_id")
    }
     $.ajax({
        type:"POST",
        url: $("#comments a.expand").attr("href"),
        data: post_data,
        success: function(){

            },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            console.log(XMLHttpRequest.responseText);
        }
    });
    return false;
});

然而我得到错误的路由信息​​如下:

ActionController::RoutingError (No route matches [POST] "/activites/1"):
Routing Error

No route matches [POST] "/activites/1"

似乎行动没有执行。

routes.rb:

Rails.application.routes.draw do


get 'account/login'

  get 'account/register' 

  get 'activites/all-events'

  post 'activites/add_in_comment'

  get 'launch' => 'activites#new'

  get 'nuts/index'

  get 'hole/all-holes'

  post 'account/login'

  post 'account/register'

  post 'activites/add'

  get 'account/logout'



  delete 'activites/delete'

  post 'activites/add_comment'


    root 'nuts#index'
    resources :nuts
    resources :activites
    resources :hole
    resources :account

end

控制器中的操作如下:

def add_in_comment
    to = params[:comment_to_id]
    content = params[:content]
    from = params[:comment_from_id]
    activity = params[:activity_id]
    com = CommentActivity.create(:activity_id =>activity, :content => content, :from_id =>from, :to_id => to)
    if com

    else 
        puts "-----------------------wrong"
        puts com.errors.full_messages
    end

end

我想知道控制器如何向ajax.thx发送响应:)

1 个答案:

答案 0 :(得分:0)

这样做:

#config/routes.rb
resources :activities do
   post :add_in_comment #-> url.com/activities/:activity_id/add_in_comment
end

#view
<%= link_to "回复", activity_add_in_comment_path(@activity) %>

#app/assets/javascripts/application.js
$(documet).on("click", ".each_comment .comment", function() {
    var post_data = {
        comment_to_id:$(this).attr("data-test1"),
        content:$(this).siblings("input").val(),
        comment_from_id:$(this).attr("data-cur_u")
    }
     $.ajax({
        type:"POST",
        url: $("#comments a.expand").attr("href"),
        data: post_data,
        success: function(){

            },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            console.log(XMLHttpRequest.responseText);
        }
    });
    return false;
});

您遇到的问题是,您可能定义了post 'activites/add_in_comment'以下的resources :activities

resources :activities
post "activities/add_in_comment"

这个问题是Rails 匹配任何传入路由与路由文件中定义的路由。当您定义resources :activities时,它会自动将url.com/activities/:id设置为show动作的路径(这是我认为您的错误)。

extra routes添加到activities资源可以解决问题。

哇你的路线可以修好:

#config/routes.rb
Rails.application.routes.draw do
    root 'nuts#index'
    resources :nuts, only: :index
    resources :holes, path: "hole", only: [] do
        get :all-holes, on: :collection
    end
    resources :activities, path_names: { new: "launch", create: "add" } do
        get  :all_events,     on: :collection
        post :add_in_comment, on: :collection
        post :add_comment,    on: :member
    end
    resources :accounts, path: "account", path_names: { create: "add" } do
        match :login,    on: :collection, via: [:get, :post]
        match :register, on: :collection, via: [:get, :post]
        get :logout,     on: :collection
    end
end

我不打算为你挑选代码。我会说你可以使用respond_withrespond_to将数据发送回ajax请求:

#app/controllers/activities_controller.rb
class ActivitiesController < ApplicationController
   def add_in_comment
       # do stuff
       respond_to do |format| 
          format.js   { ... }
          format.html { ... }
       end
   end 
end