There are a number of different ways to solve this problem. The way I imagine your app, you want to be able to comment on an item, but without having a bunch of forms rendered in the page (one for each item in a collection). Right so far? So the static (non-RJS) way to do this with jQuery is to use the DOM and JS to send the correctly unique variable to your comments controller to let it know which item you are commenting on.
# items_controller.rb
def index
@items =
Item.all.page(params[:page])
end
# views/items/index.html.erb
<ul id="items">
<%= render @items %>
</ul>
# views/items/_item.html.erb
<%= content_tag_for item, :li do %>
<%= content_tag :hi, item.headline %>
<%= simple_format item.description %>
<%- end -%>
# assets/javascripts/item_comments.js
$(document).on('turbolinks:load', function(){
$('#items li').each(function(){
var elm = $(this);
elm.append('<a href="/comments/new?item_id=' + elm.attr('id').split('_')[1] + '">Comment</a>');
});
});
That gets you a link to a CommentsController, which in turn will need to decode the (bare) attribute item_id out of its querystring, and figure out which item you are commenting on.
The #content_tag_for method, which you no doubt read the documentation for, will always create a unique id on the content tag it creates, using the instance variable you pass to it to figure out what that should be. For my contrived example, that will be 'item_123' or 'item_456' or similar. Model name, singular, lower-case, followed by an underscore, followed by the ID of the instance.
It's trivial in JavaScript (using jQuery or not) to read that attribute, split it by the underscore character, and take the number off the end. So your JavaScript stays static, uses the DOM as a data source, and you don't have to write a different link for each of the items in your list.
Walter
> To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/c5c586c2-70f7-452c-86af-b2e247482464%40googlegroups.com.