【问题标题】:How come this rails magic works?这个轨道魔法是怎么起作用的?
【发布时间】:2015-02-21 10:02:39
【问题描述】:

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

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

<%= 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>

【问题讨论】:

    标签: ruby-on-rails partial


    【解决方案1】:

    &lt;%= render @tasks %&gt; 是以下的简写:

    <% @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 渲染集合

    【讨论】:

    • 啊,亲爱的,这很有道理。谢谢!
    • @user2573222 阅读我添加到答案的链接中的文档,它解释得更好。
    猜你喜欢
    • 2013-02-04
    • 2021-12-08
    • 1970-01-01
    • 2012-05-14
    • 2019-06-14
    • 2016-05-15
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多