为什么轨道魔法有效?

时间:2014-12-23 09:19:38

标签: ruby-on-rails partial

我正在关注本教程:http://www.gotealeaf.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails

他正在使用_task partial来显示到目前为止创建的所有任务。我不明白的是为什么在这条线的部分工作原理:

<%= task.deadline %>

任务定义在哪里以及如何遍历所有任务?

_task.html.erb

<div class="row">
  <div class="col-md-5 col-md-offset-1">
    <h2>Tasks</h2>
  </div>

  <div class="col-md-2 col-md-offset-4">
    <%= link_to new_task_path, remote: true do %>
      <button class="btn btn-default">New</button>
    <% end %>
  </div>
</div>

<div class="row">
  <div class="col-md-6 col-md-offset-2" id="task-form" style="display:none;"></div>
</div>

<div class="row">
  <div class="col-md-7 col-md-offset-1" id="tasks"><%= render @tasks %></div>
</div>

控制器:

class TasksController < ApplicationController
  before_action :all_tasks, only: [:index, :create, :update, :destroy]
  before_action :set_tasks, only: [:edit, :update, :destroy]
  respond_to :html, :js

  def new
    @task = Task.new
  end

  def create
    @task = Task.create(task_params)
  end

  def update
    @task.update_attributes(task_params)
  end

  def destroy
    @task.destroy
  end

  private

    def all_tasks
      @tasks = Task.all
    end

    def set_tasks
      @task = Task.find(params[:id])
    end

    def task_params
      params.require(:task).permit(:description, :deadline)
    end
end

索引视图:

<div class="row">
  <div class="col-md-5 col-md-offset-1">
    <h2>Tasks</h2>
  </div>

  <div class="col-md-2 col-md-offset-4">
    <%= link_to new_task_path, remote: true do %>
      <button class="btn btn-default">New</button>
    <% end %>
  </div>
</div>

<div class="row">
  <div class="col-md-6 col-md-offset-2" id="task-form" style="display:none;"></div>
</div>

<div class="row">
  <div class="col-md-7 col-md-offset-1" id="tasks"><%= render @tasks %></div>
</div>

1 个答案:

答案 0 :(得分:2)

<%= render @tasks %>是:

的简写
<% @tasks.each do |task| %>
  # task object is available here so you can call task.deadline on it
<% end %>

http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials寻找 3.4.5渲染集合