I have a button on my new and edit views that sends a post request to my Letter controller through an Ajax call. If the Ajax call works perfectly in the new view, it throws a 404 error for my edit view.
Route:
post 'letters/ajax_send_test_botletter', to: 'letters#send_test_botletter', as: 'send_test_botletter'
The form is defined like this:
<%= form_for(letter, :html => {class: "directUpload", remote: true}) do |f| %>
The button triggering the Ajax call in the form:
<button class="cta3" id="send_test_letter">Send a test campaign to yourself</button>
Ajax call:
$('#send_test_letter').on('click', function(){
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: "/letters/ajax_send_test_botletter",
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
if(json['value'] == "No Recipient") {
$('#send_test_letter').css('display', 'none');
$('#save_test_user').css('display', 'block');
} else {
console.log("Success")
$('#confirmation_test_sent').html('Test successfully sent. Check your Messenger.')
}
$('form').unbind('submit');
});
return false; // prevents normal behaviour
});
});
My send_test_botletter method
def send_test_botletter
@message_content = params[:letter]['messages_attributes']['0']['content']
@button_message = params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_text'] if params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_text'] != ''
@button_url = params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_url'] if params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_url'] != ''
@cards = params[:letter]['cards_attributes'] if params[:letter]['cards_attributes'].present? == true
@test_segment = Segment.where(core_bot_id: @core_bot_active.id, name: "test").first
@recipients = BotUser.where(core_bot_id: @core_bot_active.id, source: @test_segment.token)
if @recipients.exists?
send_message_onboarding if @message_content != '' and @button_message.present? == false
send_message_button_onboarding if @message_content != '' and @button_message.present? == true and @button_url.present? == true
send_card_onboarding if @cards
respond_to do |format|
format.json { render json: {"value" => "Success"}}
end
else
respond_to do |format|
format.json { render json: {"value" => "No Recipient"}}
end
end
end
I get the following error in the Chrome console for the edit view:
POST http://localhost:3000/letters/ajax_send_test_botletter 404 (Not Found)
And in my Rails logs:
ActiveRecord::RecordNotFound (Couldn't find Letter with 'id'=ajax_send_test_botletter):
It seems it calls the Update method instead of the send_test_botletter method...
Any idea what's wrong here?