Ruby on rails 这是在Rails中布线的最佳实践吗?
说到Rails,我几乎是个业余爱好者。我得到了这个工作,但我觉得代码是不够有效的 有没有办法加快速度?这也是一个专业人士应该如何做到的 控制器Ruby on rails 这是在Rails中布线的最佳实践吗?,ruby-on-rails,performance,Ruby On Rails,Performance,说到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
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
看法
:post%>
您未读的帖子列表
:post%>
有没有什么方法可以在没有路由的情况下调用控制器中的操作?我觉得这会使工作流程更整洁。您的问题的答案是否定的。除非控制器有路由或默认生成的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
我认为将这样的操作添加到用户的控制器中不是最好的做法。如果您正在使用rails 4或只是创建一个包含所有与主题模型相关的操作的topics\u控制器,您可以尝试关注点。@Swaathi我有同样的问题。我使用过cakephp,当您在控制器
Car
中创建一个动作show_all
时,您立即拥有路径localhost/Car/show_all
。。。我穿着这样的衣服rails@mohameddiaa27“标记读取”和“标记所有读取”是用户控制器中的操作。此视图是用户显示页面。我只是担心是否每次需要访问某个操作时都需要创建一个路由。我觉得这使得应用程序非常容易受到攻击,因为URL方案是公开的。“mark_read”和“mark_as_read”在控制器中确实有路由和各自的操作。我只是不想每次需要访问控制器中的某个操作时都创建一个路由。实际上,减少自定义路由的唯一方法是将每个操作映射到其CRUD类型,在这种情况下,mark\u read
可以用update替换。但这并不是最佳实践,路由是打开应用程序的大门,它们将方法公开为操作,这意味着出于安全考虑也是如此。但如果它们公开URL和操作名称,不会对安全性造成影响吗?这将使它更容易受到攻击,对吗?您公开了执行特定功能的方法的url。您可以在控制器中处理身份验证和授权。例如:mark_all_read
将为当前用户标记已读的主题。假设rails没有路由,我可以访问sign_-in方法,我只会用我的id登录。但是,有没有办法不需要路由就可以访问某个操作?
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