我如何在Rails中渲染表及其相关项目

问题描述 投票:1回答:1

我已经在铁路中创建了脚手架项目和舞台。两者之间都存在多对一的关联。像每个项目都会有多个阶段,而用户会有多个项目。我能够呈现项目将关联的用户ID,但每个用户都会获得舞台。我可以解决这个问题吗?

project.rb

  has_many :stages

stage.rb

  belongs_to :project

项目show.html.erb,我在其中渲染项目的阶段

<div class="table-scroll">
  <table>
    <thead>
      <tr>
        <th>Stage</th>
        <th>Responsibility</th>
        <th>Status</th>
        <th>Finance</th>
      </tr>
    </thead>

    <tbody>
      <% @stages.each do |stage| %>
        <tr>
          <td><%= stage.stage %></td>
          <td><%= stage.responsibility %></td>
          <% if stage.status == true %>
            <td class="completed"><%= "Completed" %></td>
          <% elsif stage.status == false %>
            <td class="in-progress"><%= "In-Progress" %></td>
          <% else %>
            <td class="yet-to-start"><%= "Yet to Start" %></td>
          <% end %>
          <td><%= stage.finance %></td>

        </tr>
      <% end %>
    </tbody>
  </table>
</div>

projects_controller.rb

def index
    @projects = current_user.projects.all.paginate(page: params[:page], per_page: 15)
  end

  def show
    @project=Project.find(params[:id])
    @stages = Stage.all
  end

  def new
    @project = current_user.projects.build
  end

  def create
    @project = current_user.projects.build(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

stages_controller.rb

  def index
    @stages = Stage.all
  end

  def show
  end

  def new
    @stage = Stage.new
    @project = Project.find(params[:project_id])
  end


  def create
    @project = Project.find(params[:project_id])
    @stage = @project.stages.build(stage_params)

    respond_to do |format|
      if @stage.save
        format.html { redirect_to project_stages_path, notice: 'Stage was successfully created.' }
        format.json { render :show, status: :created, location: @stage }
      else
        format.html { render :new }
        format.json { render json: @stage.errors, status: :unprocessable_entity }
      end
    end
  end

我希望仅将舞台渲染到其关联的项目。我需要做什么更改?

ruby-on-rails ruby-on-rails-5
1个回答
1
投票
def show
  @project = Project.includes(:stages).find(params[:id])
  @stages = @project.stages
end
© www.soinside.com 2019 - 2024. All rights reserved.