简体   繁体   English

这是在Rails中进行布线的最佳实践吗?

[英]Is this the best practice for routing in Rails?

I'm pretty much an amateur when it comes to Rails. 关于Rails,我几乎是一个业余爱好者。 I got this to work, however I feel like the code is not efficient enough. 我可以使用它,但是我觉得代码效率不够高。

Is there any way to speed this up? 有什么办法可以加快速度吗? And also it this how a professional would do it? 而且这是专业人士会怎么做?

Controller 调节器

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

Routes 路线

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

View 视图

<% 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 %>

Is there someway that I could call an action in the controller without a route? 有没有办法可以在没有路由的情况下在控制器中调用动作? I feel it would make the workflow neater. 我觉得这会使工作流程更整洁。

The answer to your question is no. 您的问题的答案是否定的。 You can not have access any action in the controller unless it has a route, or its a CRUD generated by default, for example: 除非控制器具有路由或默认情况下生成的CRUD,否则您将无法访问控制器中的任何操作,例如:

resources :articles

generates 生成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM