To start out, I know what I am trying to do is not typical to Rails. I open to suggestions to better alternatives. I am novice with rails so suggestions are welcome 🙂
Basically, I have a notifications bar that has 5 notifications. After a user clicks and sees the notifications I want to set the a column in the database called seen to true.
Here is my Jquery function:
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div#count").html("<%= escape_javascript(render('shared/notification_count')) %>");
});
});
</script>
And here is the code I am trying to execute only after the click(located in _notification_count.html.erb)
<% notification_ids = current_user.notifications.map(&:id).join(', ')%>
<% sql = "UPDATE notifications SET SEEN = true where id IN(#{notification_ids})" %>
<% User.connection.select_all(sql) %>
However, it appears that this code is getting executed automatically when the page loads and not after the click. What is my problem?
Firstly, you cannot simply attach a
renderto your button to make changes to your database (whether it’s a read or a write). You must make an AJAX call back to your controller using something likeAnd in your controller you will handle what you need to do, and then render your js file with a
This is because when a user clicks on your button, the code will be executed on the clients side, but if you never make a request back to the server, then you will not be able to see the updated version of your database. I suggest you reading more on this, that helped me a lot.