views:

69

answers:

3

How do I place a link at the top of my page when the URL that it is pointing to is not determined until later down the page. In this example, I want to move Create and Edit Scenario links to the top of the page, but as you can see Edit Scenario depends on knowing the @scenario_id first.

<%= will_paginate @scens, :next_label => 'Older', :prev_label => 'Newer' %>
<div class="box">

<% for scenario in @scens %>
    <% @created = scenario.created_at %>
    <% @updated = scenario.updated_at %>
    <% @scenario_id = scenario.id %>
    <% if scenario.scenario_image.exists? %> 
     <%= scenario_image_tag(scenario) %>
    <% end %>
  <%= simple_format(scenario.description) %>
<% end %>
</div>

<% if session[:role_kind] == "controller" %>
    <p>
    <%= button_to "Create new scenario", :action => "create" %>
    <% if @scens.size > 0 %>
     <%= button_to "Edit scenario", :action => "edit", :id => @scenario_id %>
    <% end %>
    </p>
+1  A: 

You can add the link at the top but you will need to programmatically access it later and then assign the URL to it. That needs some kind of reference or look-up capability, I'm thinking client-side javascript but that's as I don't know Ruby.

Alternatively you could create the link later when you have the URL and place the link at the top using CSS positioning. The actual position of all the DOM elements on the page need not match the order in which they are rendered.

Dave Anderson
A: 

One way to do this is to use a helper:

In your helper.rb file:

def stack_example(scens, &block)
  html = 'Scenario Details'
  edit_link = 'Edit Link'
  yield html, edit_link
end

Then in your partial you could have something like:

<% stack_example(@scens) do |html, edit_link| %>
  <%= edit_link %><br>
  <%= html %>
<% end %>

Should output the following:

Edit Link
Scenario Details
Kenny C
A: 

I don't get it. Why do you create model in the view layer? Why wouldn't you create the model variables in the controller? Sth like:

class your_controller
  def your_method
    @scenario_id = ...
  end
end

I think that your problem lays in the invalid MVC usage. Don't you think that all the @member @variables should be initialized before the view starts to render?

Henryk Konsek