Railscast#238 jquery令牌输入 - 我的json请求转到了错误的控制器

时间:2011-07-03 23:54:23

标签: jquery ruby-on-rails-3 model-view-controller railscasts

您好我正在尝试根据railscast实现jquery令牌输入#258 http://railscasts.com/episodes/258-token-fields

当railscast使用'author'时,我正在使用'artist'

当我开始输入artist_token字段时,我的json搜索请求由UsersController#show action处理,而不是ArtistsController #index action。

由于我的_post_form部分是在PagesController#home视图上呈现的,我原以为json可能会由PagesController#home处理,但出于某种原因它是UsersController#show

任何想法我做错了什么?

## working example from railscasts #258

Started GET "/authors.json?q=d" for 127.0.0.1 at 2011-07-03 16:27:31 -0700
  Processing by AuthorsController#index as JSON
  Parameters: {"q"=>"d"}
  Author Load (0.7ms)  SELECT "authors".* FROM "authors" WHERE (name like '%d%')
Completed 200 OK in 17ms (Views: 2.3ms | ActiveRecord: 0.7ms)


## my log with UsersController#show instead of ArtistsController#index ???

Started GET "/artists.json?q=d" for 127.0.0.1 at 2011-07-03 16:12:44 -0700
  Processing by UsersController#show as JSON
  Parameters: {"q"=>"d", "id"=>"artists.json"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."cached_slug" = 'artists.json' LIMIT 1
  SQL (0.1ms)  SELECT sluggable_id FROM slugs WHERE ((slugs.sluggable_type = 'User' AND slugs.name = 'artists.json' AND slugs.sequence = 1))
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 0 LIMIT 1
Redirected to http://localhost:3000/
Completed 302 Found in 133ms

## pages controller

class PagesController < ApplicationController

  def home
    @title = "Home"
    @featured_posts = Post.featured.limit(10)
    if user_signed_in?
      @user = current_user
      @post = current_user.posts.build
      @feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
    else
     #render :layout => 'special_layout' 
    end
  end

## views/pages/home.html.erb 

<% if user_signed_in? %>

   <%= render 'shared/post_form'%>

   <%= render 'shared/user_info' %>
   <%= render 'shared/stats' %>

## views/shared/_post form.html.erb

<%= form_for @post, :validate => true, :html => {:multipart => true} do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
    <div class="field">
    <%= f.label :title, 'Title:' %><br /> 
        <%= f.text_field :title %><br />

     <%= f.label :artist_tokens, "Artists" %><br />
     <%= f.text_field :artist_tokens, "data-pre" => @post.artists.map(&:attributes).to_json %>
    <div>
    <div class="actions">
      <%= f.submit "Submit" %>
    </div>
<% end %>


## artists controller

class ArtistsController < ApplicationController
  def index
    @artists = Artist.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
      format.html
      format.json { render :json => @artists.map(&:attributes) }
    end
  end

  def show
    @artist = Artist.find(params[:id])
  end

  def new
    @artist = Artist.new
  end

  def create
    @artist = Artist.new(params[:author])
    if @artist.save
      redirect_to @artist, :notice => "Successfully created artist."
    else
      render :action => 'new'
    end
  end

  def edit
    @artist = Artist.find(params[:id])
  end

  def update
    @artist = Artist.find(params[:id])
    if @artist.update_attributes(params[:artist])
      redirect_to @artist, :notice  => "Successfully updated artist."
    else
      render :action => 'edit'
    end
  end

  def destroy
    @artist = Artist.find(params[:id])
    @artist.destroy
    redirect_to authors_url, :notice => "Successfully destroyed artist."
  end
end


## artist model

class Artist < ActiveRecord::Base
attr_accessible :name
has_many :artistizations
has_many :posts, :through => :artistizations

end

## artistization model

class Artistization < ActiveRecord::Base
attr_accessible :post_id, :artist_id
belongs_to :artist
belongs_to :post

end

## post model

  attr_accessible :title, :artist_tokens

  has_many :artistizations
  has_many :artists, :through => :artistizations 
  attr_reader :artist_tokens

  def artist_tokens=(ids)
    self.artist_ids = ids.split(",")
  end


## application.js

$(function() {
  $("#post_artist_tokens").tokenInput("/artists.json", {
    crossDomain: false,
    prePopulate: $("#post_artist_tokens").data("pre"),
    theme: "facebook"

  });
});

 ## routes 


  match 'auth/:provider/callback' => 'authentications#create'
  resources :authentications

  devise_for :admins
  match '/admin' => 'RailsAdmin/Main#index'

  devise_for :users, :controllers => {:registrations => 'registrations'}

  resources :posts do
      member do
      get :likers
      end
      collection do
        get :search
      end
  end  

  resources :relationships, :only => [:create, :destroy]
  resources :appreciations, :only => [:create, :destroy]


  match '/contact', :to => 'pages#contact'
  match '/about',   :to => 'pages#about'
  match '/help',    :to => 'pages#help'
  match '/blog',    :to => 'pages#blog'


  resources :users do
     member do
     get :following, :followers, :likes
     end
     resources :collections
 end

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id(.:format)))'
    match '/:id' => 'users#show', :constraints => {:id => /[^\/]+/}, :as => :global_user
    root :to => "pages#home"
end

1 个答案:

答案 0 :(得分:0)

通常当您遇到类似问题时,“错误”控制器正在处理某些内容时,您应首先检查routes.rb文件。

我马上注意到了这一点:

# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
match '/:id' => 'users#show', :constraints => {:id => /[^\/]+/}, :as => :global_user

基本上,似乎该格式的每个请求都被路由到users#show操作。尝试评论match指令并查看它是否现在有效。如果其他事情破裂,那么由你来决定你为什么需要它,以及如何适应。