0

私はレールに不慣れで、この質問に対する回答に従いました。

これが私のプロジェクトの様子です:

コントローラ:

def create
  def create
      current_user.likes.create(:post_id => params[:post_id])
      render :layout => false
   end
end

.js ファイル:

$ ->
    $(".like").click ->
        post_id = $(this).attr('id')
        $.ajax
            type: 'POST'
            url: 'likes/' + post_id
            success: ->
                alert "succsess!"

Routes.rb

Sample::Application.routes.draw do
  resources :likes

  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  resources :posts, only: [:create, :destroy]

  root              to: 'pages#home'
  match '/about',   to: 'pages#about'
  match '/contact', to: 'pages#contact'
  match '/help',    to: 'pages#help'
  match '/signup',  to: 'users#new'
  match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy'
  post  '/likes/4', to: 'likes#create', :as => :like
end

(私は提案をテストするために「/likes/4」を使用します (将来的には「post_id」になります))。

ビューの [いいね] ボタンをクリックすると、いいねがデータベースに保存されますが、このエラーが発生します (Chrome のインスペクターでコンソールを見ると)...

POST http://0.0.0.0:3000/likes/4 500 (Internal Server Error)

...そして、ajaxから成功のアラートを受け取ることはありません。

を実行するwget --post-data='' http://localhost:3000/likes/4と、次のようになります。

--2012-07-22 19:35:01--  http://localhost:3000/likes/4
Resolving localhost... ::1, 127.0.0.1, fe80::1
Connecting to localhost|::1|:3000... failed: Connection refused.
Connecting to localhost|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response... 500 Internal Server Error
2012-07-22 19:35:02 ERROR 500: Internal Server Error.

このエラーの原因を知っている人はいますか?

4

2 に答える 2

0

それは、あなたが投稿を行い、ルートが get であるためだと思います。コマンドを録音すると表示できますrake routes。ajax リクエスト タイプを GET に変更するか、ルートを変更してみてください。matchで置き換えpostます。

于 2012-07-21T17:19:26.357 に答える
0

わかりました、私は問題を見つけました!

まず、途中で私を助けてくれたいくつかの良い点を作ってくれた Dougui に感謝します!

解決:

一意性の検証を次のように変更する必要がありました。

validates :tag, :uniqueness => {:scope => :post}

に:

validates :tag_id, :uniqueness => {:scope => :post_id}

なぜだろう?ここで説明されています: http://thetenelements.blogspot.no/2011/08/undefined-method-text-for-nilnilclass.html

物事が機能しているときの私のファイルは次のとおりです。

like.rb

  validates :user_id, :uniqueness => {:scope => :post_id}
  belongs_to :user
  belongs_to :post

likes_controller.rb

def userLikePost
   current_user.likes.create(:post_id => params[:post_id])
end

ルート.rb

match '/likes/:post_id', to: 'likes#userLikePost'

pages.js.コーヒー

$ ->
    $(".like.btn.btn-mini").click (e) ->
        if $(this).attr("class") == "like btn btn-mini"
            post_id = $(this).attr('id')
            $.post '/likes/' + post_id
        e.stopImmediatePropagation();
        $(this).addClass("active")

html ボタン

<button class="like btn btn-mini" id="<%= feed_item.id %>"><i class="icon-heart"></i></button>

そして、私が持っているユーザーとポストモデルでhas_many: likes

これが他の人に役立つことを願っています:)

于 2012-07-24T10:59:11.260 に答える