Richlewis
Richlewis

Reputation: 15374

Render partial dependent upon which link_to clicked

I have a list of links that when clicked I would like it to show its relevant partial via Ajax, i have successfully rendered the first one but want to implement some if statements to recognise which link_to has been clicked. How do i differentiate the links?

<ul class="nav nav-tabs">
<li><%= link_to 'Home', posts_path %></li>
<li><%= link_to 'Tynewydd', posts_path, :remote => true %></li>
<li><%= link_to 'Woodside', root_path %></li>
<li><%= link_to 'Sandpiper', root_path %></li>
<li><%= link_to 'Outreach', root_path %></li>
<li><%= link_to 'Company', root_path %></li>
<li><%= link_to 'Staff', root_path %></li>
</ul>

index.js.erb

$('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');

I was thinking something like this

<% if params[:tynewydd] %>
$('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');
<% end %>

but what to use as the params?

Anyone have any ideas, bit stuck here

Upvotes: 2

Views: 1539

Answers (3)

rossta
rossta

Reputation: 11494

I suggest using a single param key (like view) for which the value will be the name of a partial. If the given name does not map to a partial, you should provide a default partial. It could look something like this:

# methods available to controllers and helpers
def post_partials
  %w[home tynewydd]
end

def root_partials
  %w[woodside sandpiper outreach company staff]
end

# posts controller
@view = post_partials.detect?(params[:view]) || 'home'

# home controller
@view = root_partials.detect?(params[:view]) || 'woodside'

# view
<ul class="nav nav-tabs">
  <li><%= link_to 'Home', posts_path(:view => 'home') %></li>
  <li><%= link_to 'Tynewydd', posts_path(:view => 'tynewydd', :remote => true %></li>
  <% root_partials.each do |partial| %>
    <li><%= link_to partial.titelize, root_path(:view => partial) %></li>
  <% end %>
</ul>

<%= render @view %>

Upvotes: 2

R Milushev
R Milushev

Reputation: 4315

You can pass values by link_to like this :

  <li><%= link_to 'Sandpiper', select_partial_path(option: "other_partial") %></li>

which will give you an :option symbol in your select_partial action of your controller . It's up to you how it could be used to select partial for rendering.

Upvotes: 1

Manoj Monga
Manoj Monga

Reputation: 3083

Try altering your link to look like:

<%= link_to 'Tynewydd', posts_path(:type => 'Tynewydd'), :remote => true %>

And then in your index.js.erb:

<% if params[:type] == 'Tynewydd' %>
  $('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');
<% end %>

Upvotes: 3

Related Questions