简体   繁体   中英

how to display one controller show action in another controller action in rails

I am using two controller incident and incident_list, i am displaying all incidents in incident_list/index page when click on show button in each incident i want to display that incident details

IncidentListController

def show
   @incidents = Incident.all
   @incident = Incident.find(params[:id])
   render "incidents/show"
 end

IncidentController

def show
  @incidents = Incident.all
  @incident = Incident.find(params[:id])
 end

incidnet_lists/index.html.erb

<table>
  <table class="table table-striped table-bordered">
   <thead >
  <tr>
      <th class="c2">Case ID</th>
      <th class="c2">Call Type</th>
      <th class="c2">Number of People</th>
      <th class="c2"></th>

  </tr>
 </thead>
<tbody>
  <tr>
    <td><%= inc.id %> </td>
    <td><%= inc.call_type %> </td>
    <td><%= inc.no_of_people %></td>
    <td><%= link_to 'Show', @incidents %></td>

  </tr>
 </tbody>
</table> 

incidents/show.html.erb

 <table class="table table-striped table-bordered">
   <thead>
     <tr>
       <td class= "c2" > Case Id </td>
       <td class= "c2"> Caller Name </td>
       <td class="c2"> Contact Number </td>
       <td class= "c2"> Calling For </td>
       <td class="c2"> Call Type </td>
      <tr>
      </thead>
     <tbody>
       <% @incidents.each do |inc| %>
       <tr>
         <td> <%= inc.id %> </td>
         <td> <%= inc.caller_name %></td>
         <td> <%= inc.contact_number %></td>
         <td> <%= inc.for_whom %> </td>
         <td> <%= inc.call_type %> </td>
       </tr>
       <% end %>
     </tbody>
   </table>

when click on show button in the incident_list page incident show page should be display

Your situation is perfectly covered by REST approach.

According to that approach you should have the single IncidentsController controller. Then you should have

  1. show action which would expose particular incident to show.html.erb view as @incident instance variable
  2. index action which would expose the list of all (or some) incidents to index.html.erb view as @incidents instance variable.

So you don't need and should not call some controller's action from another controller's action.

It's the "Rails Way", it's the "REST Way". It's the way how one should do that.

The simplest tip in your situation is generate rails scaffold for your incidents resources and use the generated files properly to set up things.

rails generate scaffold Incident

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