简体   繁体   中英

Is this the best practice for routing in Rails?

I'm pretty much an amateur when it comes to 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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