Rails click button, run the code and display output

Hello,

I am learning Rails framework these days and wanted to understand a very simple case where say I have a index page where I have a button. I need to click this button and have the controller run some code(example - return sum of 2 numbers)associated to this button(The code returns some values stored in variables). The O/P of this controller method(or function) needs to be displayed on the same index page(or maybe redirect to new page). Not sure how to achieve this?

for fun I checked how AI would answer this question:

not too shabby check it out

Thank you @oystersauce8 so much for it.I am checking this now…

Hi @oystersauce8 ,

So, I am using the post method to display results on a new page(/calculate). Upon clicking “Calculate” Button, the page gives below errors on console(Developer Tools).

Error: Form responses must redirect to another location

I got it fixed by adding below in index.html.erb

data: { turbo: false }

So, the form_tag looks as below:

<%= form_tag calculate_path, data: { turbo: false }, method: :post do %>

Thanks a lot @oystersauce8 for showcasing the end to end workflow !

Hi @oystersauce8 ,

I have one question and still struggling to find answers. I wanted to know what’s the syntax of the form_tag we used index file? The _path variable it uses is mapped to the controller method ? Also if I need to change the post URL to say “/results” from the present “/calculate” then what changes will be required? I see that you have the term “calculate” everywhere - index.html.erb, calculate.html.erb and routes.rb.

You might want to start a new thread about this question. There are a lot of ways to do what you describe, and which one you choose may depend a lot on what else you know about the user who is clicking the button, etc. Any additional details about the user interaction that you know would be valuable to help someone answer your question.

Walter

Hi there, here is the second opinion, let me know if it works or if the alien technology lied about it:

https://chat.openai.com/share/4bbca980-19e2-47f8-8acd-fab5102419c1

on a side note. maybe the forum should have a vetted FAIQ page for llm answers to common questions not (adequately) covered in the guides? (vetted as in they have comments were people can point out things about the answer)