2014-10-29 67 views
1

當談到Rails時,我幾乎是一個業餘愛好者。我得到了這個工作,但我覺得代碼效率不夠高。這是在Rails中路由的最佳實踐嗎?

有什麼辦法可以加快速度嗎?而且這也是專業人員如何做到的?

控制器

def mark_read 
    @topic = Topic.find(params[:id]) 
    @topic.mark_as_read! :for => current_user 
    redirect_to user_path(current_user.slug) 
end 

def mark_all_read 
    Topic.mark_as_read! :all, :for => current_user 
    redirect_to user_path(current_user.slug) 
end 

路線

resources :users do 
    member do 
    post :mark_read 
    post :mark_all_read 
    end 
end 

查看

<% if current_user.id == @user.id %> 
<%= link_to "Mark all as read", mark_all_read_user_path, :method=> :post %> 

<h4> List of posts unread by you </h4> 
<% @unread.each do |topic| %> 
<% if @user.following?(Product.find(topic.product_id)) %> 
<li> <%= topic.title %> <%= link_to "Mark as read", mark_read_user_path(topic), :method=> :post %> </li> 
<% end %> 
<% end %> 

有什麼方法,我可以調用控制器的動作沒有一個路線?我覺得它會使工作流程更加簡潔。

+0

我認爲它不是最好的做法,以增加這樣的行爲給用戶的控制器。如果您使用的是rails 4,或者只是創建一個包含與Topic模型相關的所有操作的topics_controller,則可以嘗試關注。 – mohameddiaa27 2014-10-29 10:55:30

+0

@Swaathi我有同樣的問題。我和cakephp一起工作,當你在控制器'Car'中立即創建一個動作'show_all'時,你有路徑'localhost/Car/show_all' ...我在rails – inye 2014-10-29 15:36:59

+0

@ mohameddiaa27中看到了一些像這樣的「mark_read」和「mark_all_read」是用戶控制器中的操作。這個視圖是用戶顯示頁面。每次需要訪問某個操作時,我都會關心是否需要創建路由。由於URL方案暴露出來,我覺得這會讓應用程序非常脆弱。 – 2014-10-31 03:01:42

回答

0

你的問題的答案是否定的。你不能訪問控制器的任何行動,除非它有一個路線,或默認生成的一個CRUD,例如:

resources :articles 

產生

Controller#Action 
    articles GET /articles(.:format)   articles#index 
      POST /articles(.:format)   articles#create 
new_article GET /articles/new(.:format)  articles#new 
edit_article GET /articles/:id/edit(.:format) articles#edit 
    article GET /articles/:id(.:format)  articles#show 
      PATCH /articles/:id(.:format)  articles#update 
      PUT /articles/:id(.:format)  articles#update 
      DELETE /articles/:id(.:format)  articles#destroy 
+0

「mark_read」和「mark_as_read」在控制器中確實有路由和相應的動作。每次我需要訪問控制器中的操作時,我都不想創建路由。 – 2014-10-31 03:02:52

+0

實際上,減少自定義路由的唯一工作就是將每個動作映射到其CRUD類型,在這種情況下'mark_read'可以被更新替代。但這不是最好的做法,路線是對你的應用敞開大門,他們暴露的方法是行動,其意圖是爲了安全。 – mohameddiaa27 2014-10-31 03:08:37

+0

但是,如果他們暴露的網址和行動名稱不會影響安全性?這會讓它更容易受到傷害嗎? – 2014-10-31 03:16:33