未捕获的错误:缺少路由参数:id - Javascript控制台

时间:2014-11-04 00:43:22

标签: javascript ruby-on-rails ajax routes

这是我第一次尝试使用ajax和javascript而且我遇到了这个问题:

未捕获错误:缺少路径参数:id

我不知道如何解决它/在哪里看,因为我不明白错误告诉我的是什么。什么'路线参数缺失:id'是什么意思?

我不确定哪个代码与此问题相关,所以我发现了一些可能重要的内容:

我的浏览器显示:

javascript console in chrome

我认为它与用户变量如何传递有关,但我不确定这个想法是否在正确的轨道上......

用户/控制器:

  def index
    @users = User.search(params[:search])
  end

查看/用户/索引:

<ul>
    <% @users.each do |user| %>
        <li>
            <%= user.name %>
            <% if logged_in? %>
                <div id="relationship-status">
                    <% if current_user.following.include?(@user) %>
                        <%= link_to "Edit Relationship", edit_relationship_path(followed_id: @user), class: "btn btn-primary" %>
                    <% else %>
                        <%= link_to "Add Relationship", new_relationship_path(followed_id: @user), class: "btn btn-primary", id: 'add-relationship', data: { followed_id: @user.to_param } %>
                    <% end %>
                </div>
            <% end %>   
        </li>
    <% end %>
</ul>

relationship_controller:

def create
    if params[:relationship] && params[:relationship].has_key?(:followed_id)
      @followed = User.find(params[:relationship][:followed_id])
      # @followed = User.where(name: params[:relationship][:followed_id]).first
      @relationship = Relationship.request(current_user, @followed)
      respond_to do |format|
        if @relationship.new_record?
          format.html do
            flash[:danger] = "There was a problem creating that relationship request"
            redirect_to followed_path(@followed)
          end
          format.json { render json: @relationship.to_json, status: :precondition_failed }
        else
          format.html do
            flash[:success] = "Friend request sent"
            redirect_to followed_path(@followed)
          end
          format.json { render json: @relationship.to_json }
        end

      end
    else
      flash[:danger] = "Friend Required"
      redirect_to users_path
    end
  end

relationship.js:

$(document).ready(function() {

    $('#add-relationship').click(function(event) {
        event.preventDefault();
        var addRelationshipBtn = $(this);
        $.ajax({
            url: Routes.relationship_path({relationship: { followed_id: addRelationshipBtn.data('followedId') }}),
            dataType: 'json', 
            type: 'POST', 
            success: function(e) {
                addRelationshipBtn.hide();
                $('#relationship-status').html("<a href='#' class='btn btn-success'>Relationship Requested</a>")
            }
        });
    });
});

编辑:已添加:

的application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .
//= require js-routes

配置/ application.rb中:

class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
    config.assets.initialize_on_precompile = true
  end
end

路线:

Rails.application.routes.draw做

  root                       'static_pages#home'
  get     'help'     =>      'static_pages#help'
  get     'about'    =>      'static_pages#about'
  get     'contact'  =>      'static_pages#contact'
  get     'signup'   =>      'users#new'
  get     'login'    =>      'sessions#new'
  delete  'logout'   =>      'sessions#destroy'
  get     'search'   =>      'users#index'
  get     'followed' =>      'users#show_followed'
  resources :users do 
    member do 
      get :following, :followers
    end
  end
  resources :sessions,            only: [:new, :create, :destroy]
  resources :account_activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
  resources :profiles,            only: [:edit, :update, :destroy] do
    put :email, on: :member
  end
  resources :relationships,       only: [:new, :create, :index, :edit, :accept, :destroy] do
    member do
      put :accept
    end
  end

1 个答案:

答案 0 :(得分:1)

不可否认,我没有使用过JS路由,但我认为您的问题是由于您使用的是Routes.relationship_path而不是Routes.relationships_path。请注意,前者是单数(这就是路由期望id为关系的原因)关系,而relationships_path应该链接到集合。

Routes.relationships_path() // => "/relationships"
Routes.relationships_path(1) // => "/relationships/1"

$(document).ready(function() {

    $('#add-relationship').click(function(event) {
        event.preventDefault();
        var addRelationshipBtn = $(this);
        $.ajax({
            // note relationships - not relationship
            url: Routes.relationships_path(),
            data: {
              relationship: { followed_id: addRelationshipBtn.data('followedId') }
            },
            dataType: 'json', 
            type: 'POST', 
            success: function(e) {
                addRelationshipBtn.hide();
                $('#relationship-status').html("<a href='#' class='btn btn-success'>Relationship Requested</a>")
            }
        });
    });
});

另一个问题是,您尝试在查询参数中传递followed_id而不是POST请求正文。