Reputation: 421
I am trying to load a partial when the user clicks on a div element. My problem is that I want to pass variables to this partial and I can't find a way.
I have written the following code:
<script>
$(".conversation").click(function() {
<% @conversationId = capture do %>
<%= javascript_tag "$(this).attr('id');" %>
<% end %>
$("#conversation").html("<%= escape_javascript(render(:partial => 'conversations/conversation_home', :locals =>{:conversation => Conversation.find_by_id(@conversationId)} )) %>");
});
</script>
I am attempting to initialize a varialbe (@conversationId) and then use it to pass the object I want to the partial. When I load my page it attempts to load the partial as well (why? I did not click anywhere), and I get a "undefined method `subject' for nil:NilClass" because conversation is nil. If I replace @conversationId with a value conversation is initialized correctly.
Why does the partial get rendered when I load the page, instead after I click on the div? And do I initialize @conversationId properly?
Is there another approach I could take?
Upvotes: 1
Views: 96
Reputation: 1954
Anything between <%
and %>
gets evaluated when the page loads. Thats the expected behavior and thats why your partial is being loaded on page load.
Use AJAX
I would personally use AJAX. This is how I would do it.
In HTML (Add a div for each conversation with its id
)
<div class="conversation" data-conversation-url="<%= conversation_path(:id => 1) %>">Get Conversation</div>
In Javascript (I would put it in a separate file)
$(document).on('click', '.conversation', function() {
$.get({
url: $(this).data('conversation-url'),
success: function() {
// do something here
},
failure: function() {
// do something here
}
});
});
In conversations_controller
def show
@conversation = Conversation.find(params[:id])
end
In views/conversations/show.js.erb
$("#conversation").html("<%= escape_javascript(render(:partial => 'conversation_home', :locals =>{:conversation => @conversation} )) %>");
This should do the trick.
Please note that this is assuming that you have the route already set for conversation_path
.
Also, this is just a sample code. You will have to modify it to fit your needs, add error handling and may be change some code based on the version of jQuery and Rails that you are using.
Upvotes: 2