0

I've got two models : canvas an block

I've got canvas who all have 9 blocks linked to them.

canvas/show.html.erb

<body >
  <table class="table canvas" cellspacing=0 >
    <tr class="twenty">
      <th colspan=2>KP</th>
      <th colspan=2>KA</th>
      <th colspan=2>VP</th>
      <th colspan=2>CR</th>
      <th colspan=2>CS</th>
    </tr>
    <tr class="twenty" >
      <td rowspan=3 colspan=2 >
        <%= render :partial => @blocks[0], :locals => { :id_block => 0 } %>
        </td>

(...)

</table>
</body>

Here is my controller :

class CanvasController < ApplicationController

  before_filter :authenticate_user!

  def show 
    @blocks=Array.new
    9.times do |acc|
      @blocks << Block.find_or_create_by_id_case_and_canvas_id(acc+1,params[:id])
    end
  end

  def index
    @canvas=Canvas.all
  end
end

In each canvas, I ant to render some partials corresponding to my Blocks and in those partials I need to have the id of the block I am rendering.

blocks/-block.html.erb

<%= id_block %>

The problem is that the local variable id_block is not recognized in this partial.

I've tried all sorts of ways to write the render like :

        <%= render @blocks[0], :id_block => 0 %>
        <%= render :partial => "blocks/block", :locals => { :id_block => 0 } %>
        <%= render :partial => "blocks/block", :id_block => 0 %>

I'm kind of out of ideas now...if someone knows why, he is welcome, thanks :)

4

1 回答 1

0

好的,所以...由于我的评论解决了问题,我将发布一个更清晰的答案。:)

首先,部分文件名应始终以下划线开头:“_”而不是“-”。:) 这是一个约定(据我所知,根本没有加载以“-”开头的部分......)。;)

其次,做你想做的事的一个干净的解决方案是将你的块作为对象传递给 partial,如下所示:

<%= render :partial => "blocks/block", :object => @blocks[0] %>

它的作用是......在您的部分中,您将拥有一个与部分名称完全相同的对象。因此,如果您将部分命名为“_block”,您将在部分的“块”变量中存储一个对象“块”。

但是,如果您将部分命名为“_canvas_block”,则该变量将在您的部分中命名为“canvas_block”。

如您所见,这与当地人的工作方式略有不同,但这样做确实更清洁。:)

然后在你的部分,因为你现在有一个块对象存储在块变量中,你只需要调用:

<%= block.id %>

ruby 指南第 3.4.4 章中的更多信息。

您也可能对阅读下一章 3.4.5 非常感兴趣,该章处理将“集合”传递给部分。:)

于 2013-08-12T13:38:31.380 回答