简体   繁体   中英

ruby on rails - Do Loop in a controller

I would like to display every files that belong to one given project (the relationship works fine, could check it using the Rails console). Here is my 'Project' controller , I may need a do loop (to loop through each files , for 1 project) but I'm not sure :

def show
@project = Project.find(params[:id])
@pfile = Project.find(params[:id]).Pfiles.find(:all)

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @project }
  format.xml  { render :xml => @pfile }
end
end

This is my 'Project' view :

  <p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @project.name %>
</p>

<p>
  <b>Description:</b>
  <%= @project.description %>
</p>

<p>
  <b>Files:</b>
  <%= @project.pfile.name %>
</p>

<%= link_to 'Edit', edit_project_path(@project) %> |
<%= link_to 'Back', projects_path %>

Thanks :)

If the relationship is set up correctly you can do this:

controller

@pfiles = @project.pfiles

view

<p>
  <b>Files:</b>
  <% @pfiles.each do |pfile| %>
    <%= pfile.name %>
  <% end %>
</p> 

easier yet... rely on the magic of rails.

in the controller

@project = Project.find(params[:id])
@pfiles = @project.pfiles

then in the view

<b>Files:</b>
<%= render @pfiles %>

then in views/pfiles/_pfile.html.erb

<%= pfile.name %>

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