如何正确地将参数传递给控制器​​?

问题描述:

  1. 从show view:我想通过显示的消息的ID放弃行动和垃圾邮件。如何正确地将参数传递给控制器​​?

  2. 从索引视图:我想通过检查消息的ID放弃行动,并一次性垃圾。

但是我只能立即垃圾一条记录,即使我检查多个并从索引视图提交。
我怎样才能同时存档1和2?

路线

match 'messages/discard(/:id)' => 'messages#discard', :via => :post , :as => :discard_messages 

索引视图

<%= form_tag(:action => discard, :via => 'post') do %> 
    <% @messages.each do |m| %> 
     <tr> 
     <td><%= check_box_tag "id",m.id %></td> 
     <td><%= m.last_message.id %></td> 
     <td><%= 'unread' if m.is_unread?(current_user) %></td> 
     <td><%= m.last_message.created_at.to_s(:jp) %></td> 
     <td><%= m.last_sender.username %></td> 
     <td><%= link_to m.subject, show_messages_path(:id => m, :breadcrumb => @box) %></td> 
     </tr> 
    <% end %> 
    <%= submit_tag "discard", :class => 'btn' %> 
    <% end %> 

放映视图

<%= link_to 'Discard', discard_messages_path(@messages), :class => 'btn', :method => 'post' %> 

控制器

def discard 
     conversation = Conversation.find_all_by_id(params[:id]) 
    if conversation 
     current_user.trash(conversation) 
     flash[:notice] = "Message sent to trash." 
    else 
     conversations = Conversation.find(params[:conversations]) 
     conversations.each { |c| current_user.trash(c) } 
     flash[:notice] = "Messages sent to trash." 
    end 
     redirect_to :back 
    end 

使用[]命名在你的HTML,其轨道,然后将提供作为PARAMS数组

index.html.erb

<td><%= check_box_tag "message_id[]", m.id %></td> 

控制器

# ... 
else 
    conversations = Conversation.where("id IN (?)", params[:message_id][]) 
    # ... 

为了进一步简化事情,我会删除您的动作中的条件并创建两个单独的动作

routes

resource :messages do 
    member do 
    post 'discard' # /messages/:id/discard 
    end 
    collection do 
    post 'discard_all' # /messages/discard_all?message_id[]=1&message_id[]=22 
    end 
end