Spencer
Spencer

Reputation: 22408

Rails: How to get Jquery to update a database column after a click

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?

Upvotes: 2

Views: 2338

Answers (2)

vinceh
vinceh

Reputation: 3510

Firstly, you cannot simply attach a render to 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 like

$.ajax({
    url: "/path/to/your/method",
    type: "GET",
    dataType: "script"
});

And in your controller you will handle what you need to do, and then render your js file with a

respond_to do |format|
    format.js {render 'shared/notification_count'}
end

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.

Upvotes: 3

user483040
user483040

Reputation:

The contents of your .erb files are simply templates: the are evaluated at load time. If you want the user interaction to trigger some behavior, you have to do it purely in javascript. As a result, the way to have the database interactions occur are in this chain:

  1. user does something
  2. javascript talks to the controller (via either ajax or by submitting a form)
  3. The controller gets the model in question and asks it to do something
  4. the model interacts with the database.

So basically in your model you need to have code to fire those notifactions. The controller will ask the model to do so only when it receives a request from the user/view to do so.

Upvotes: 2

Related Questions