davidic2ofu
davidic2ofu

Reputation: 37

Update model field with button Rails

I have a messaging system in my Rails 5 project where the Message model has an isread field to indicate whether the recipient has read the message yet or not.

I'm using a bootstrap modal to view the message and would like the message's isread field to change to true when the modal is closed.

Could someone explain how to do this from the button_tag or make the button tag call method in the controller to do it?

Something like:

message.isread = true
message.save!

to execute when the "Close" button is pressed from my view:

<div id="modal1<%= index %>" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><%= message.subject %></h4>
      </div>
      <div class="modal-body">
        <p><%= message.content %></p>
      </div>
      <div class="modal-footer">
        <%= button_tag "Close", :class => "btn btn-default", "data-dismiss" => "modal" %>
      </div>
    </div>
  </div>
</div>

Thank you!

Upvotes: 1

Views: 1082

Answers (2)

Sovalina
Sovalina

Reputation: 5609

You can define a new action in your controller which update the attribute isread to true and use the button_to helper

#routes
resources :messages do
  post :is_read, on: :member
end  

#messages controller
def is_read
  @message = Message.find(params[:id])
  @message.update(isread: true)
  redirect_to ...
end

#view
<%= button_to "Close", is_read_message_path %>

Upvotes: 1

ricks
ricks

Reputation: 3324

If you want a button click to call a method in your controller you will need to first capture the action of the button click in javascript

$(".btn-default").click(function(){

});

Then you want to do an Ajax call to the controller method

$.ajax({
    url: "/message/update_is_read",
    type: "POST",
    data: {is_read: isRead},
    success: function(resp) {
        console.log(resp);  
    },
    error: function(resp) {
        console.log(resp);
    },
});

then in your controller catch it with

def update_is_read
     is_read = params[:is_read]

end

Make sure you make add the path to your routes

  post '/messages/update_is_read', to: 'messages#update_is_read', as: '/messages/update_is_read'

You can modify the controller code to save.

Upvotes: 0

Related Questions