2012-05-22 131 views
0

我正在使用名爲Recommendable的David Celis gem在我的rails應用中實現一個類似的系統。我已經得到了一切工作在控制檯,但我不能得到正確的路線,我得到了「無路線匹配[GET]」/類別/ 1 /職位/ 1 /像「的錯誤。我在我的模型如下:爲控制器動作添加路由

class Category < ActiveRecord::Base 
    has_many :posts, :dependent => :destroy 
    extend FriendlyId 
    friendly_id :name, use: :slugged 
end 

class Post < ActiveRecord::Base 
    belongs_to :category 
end 

在我的崗位控制器I有:

class PostsController < ApplicationController 
    before_filter :authenticate_user! 
    before_filter :get_category 
    def like 
    @post = Post.find(params[:id]) 
    respond_to do |format| 
     if current_user.like @post 
     else 
     flash[:error] = "Something went wrong! Please try again." 
     redirect_to show_post_path(@category, @post) 
     end 
    end 
    end 
end 

在我的路線,我有:

​​

有人可以指出我的錯誤嗎?我可以讓PUT工作,但我不知道GET錯誤是從哪裏來的,因爲如果用戶喜歡某個帖子時發生錯誤,我正在嘗試重定向到帖子。先謝謝你。

編輯:

在我看來,我有:

- title "#{@post.class}" 
%p#notice= notice 

%p 
    %b Title: 
    = @post.title 
%p 
    %b Description: 
    = @post.description 
%p 
    %b Likes: 
    = @post.liked_by.count 

= link_to 'Edit', edit_category_post_path(@post) 
\| 
= link_to 'Back', category_posts_path 
\| 
= link_to 'Like', like_category_post_path(@post) 
+0

你怎麼努力達成你的'like'行動?你爲此創建了一些鏈接/按鈕嗎?向我們展示模板的代碼。 – jdoe

回答

1

替換:

= link_to 'Like', like_category_post_path(@post) 

有:

= link_to 'Like', like_category_post_path(@category, @post), method: :put 

或者,因爲我喜歡它:

= link_to 'Like', [@category, @post], method: :put 

我覺得你like必須是:

def like 
    @post = Post.find(params[:id]) 
    respond_to do |format| 
    format.html do 
     if current_user.like @post 
     flash[:notice] = "It's ok, you liked it!" 
     redirect_to :back 
     else 
     flash[:error] = "Something went wrong! Please try again." 
     redirect_to show_post_path(@category, @post) 
     end 
    end 
    end 
end 
+0

嗨jdoe,謝謝你的幫助!我現在正在接近。由於某種原因,當我這樣做的事務是在數據庫中執行的,但重定向不工作,因爲我留在http:// localhost:3000/categories/1/posts/1/like後點擊我的鏈接。這個網站是空白的,所以我沒有收到任何錯誤,你知道這是爲什麼嗎?當我運行耙路線時,我得到這個:show_post /categories/:category_id/posts/:id(.:format)posts#show like_category_post PUT/categories /:category_id/posts /:id/like(。:format)posts#like –

+0

你發佈了你的'like'動作的完整代碼嗎?它似乎並不完整,它不完整! – jdoe

+0

是的,我喜歡的行爲是我完整的代碼。我發現它在網上的某個地方,它被寶石開發者作爲例子共享,而且我儘管已經完成了。這是我第一個複雜的rails應用程序,所以我掙扎了一下。你覺得缺少什麼? –

1

你的路線需要一個PUT要求,當你發出GET請求。

你要麼需要通過button_to:method => :put讓您的應用程序發出PUT請求(正確的解決方案)來訪問你的路線,或者改變您的路線使用GET請求(錯誤的方式,使該修改狀態請求):

 get :like, :on => :member 
+0

不要這樣做!它打破了每一本關於Rails的正派書籍中陳述的所有事情:不要使用GET來改變狀態! **我很好奇誰是upvoted這個瘋狂的假設!** – jdoe

+0

不幸的是,這是行不通的。如果我改變路線來取代而不是在數據庫中發生事務。在另一種情況下,如果在我看來我添加:method =>:put我得到一個錯誤「錯誤的參數數量(0爲1)」。感謝您的幫助! –

+0

正如@ jdoe所說,你不應該使用改變路線的解決方案。解決此問題的正確方法是讓您的應用發出PUT請求。 – meagar