Question

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 :)

Was it helpful?

Solution

Ok, so... As my comment solved the problem, I'll post a cleaner answer. :)

First, a partial file name should always start with an underscore: "_" and not with a "-". :) This is rather a convention (and as far as I know a partial starting with a "-" isn't loaded at all...). ;)

Second, a clean solution to do what you want is to pass your block as an object to the partial, like this:

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

What it does is... that in your partial you will have an object with the exact same name as the partial's name. So if you named your partial "_block" you will have an object "block" stored in the "block" variable in your partial.

But if you named your partial "_canvas_block", the variable would then be named "canvas_block" inside your partial.

This works a little bit different from locals as you can see, but it's really cleaner to do it this way. :)

Then in your partial, as you now have a block object stored in the block variable, you just have to call:

<%= block.id %>

A little bit more information in the ruby guide chapter 3.4.4.

You also may be highly interested in reading the next chapter 3.4.5 which deals with passing "collections" to partials. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top