如何在rails中的2嵌套模型中的show.html.erb中执行另一个show动作

时间:2015-12-07 17:39:15

标签: ruby-on-rails

我有2个模型 - TaskProject

现在我已经在项目中嵌套了我的任务,我可以在views/project/show.html.erb内创建一个新任务。

现在我要做的就是在里面做另一个表演动作

  

<tbody> <% @tasks.each do |task| %> <tr> <td><%= task.name %></td> <td><%= task.description %></td> <td><%= link_to 'Show', project_task_path(@task,:project_id) %></td> </tr>
<% end %> </tbody>

  class TasksController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy]
  before_action :set_project
  # GET /tasks
  # GET /tasks.json
  def index
    @tasks = Task.all
  end

  # GET /tasks/1
  # GET /tasks/1.json
  def show
     @tasks = Task.where(project_id: @project.id)
  end

  # GET /tasks/new
  def new
    @task = Task.new
  end

  # GET /tasks/1/edit
  def edit
  end

  # POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(task_params)
    @task.project_id = @project.id

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

  # PATCH/PUT /tasks/1
  # PATCH/PUT /tasks/1.json
  def update
    respond_to do |format|
      if @task.update(task_params)
        format.html { redirect_to @task, notice: 'Task was successfully updated.' }
        format.json { render :show, status: :ok, location: @task }
      else
        format.html { render :edit }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.json
  def destroy
    @task.destroy
    respond_to do |format|
      format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

    def set_project
      @project = Project.find(params[:project_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_params
      params.require(:task).permit(:name, :description)
    end
end

1 个答案:

答案 0 :(得分:0)

你最好看partials

  

部分模板 - 通常只是称为&#34;部分&#34; - 是另一种将渲染过程分解为更易于管理的块的设备。使用partial,您可以移动代码以将特定的响应片段呈现给自己的文件。

在您的情况下,您将能够使用项目的相关任务填充部分内容:

#app/views/projects/show.html.erb
<table>
   <%= render @project.tasks %>
</table>

#app/views/projects/_task.html.erb
<tr>
   <td><%= task.name %></td>
   <td><%= task.decription %></td>
   <td><%= link_to 'Show', project_task_path(task,@project) %></td>
</tr>

根据我的理解,这应该回答你的问题......?