Home > Net >  Change label's value on form submit - Ruby on Rails
Change label's value on form submit - Ruby on Rails

Time:11-07

I am brushing up on my rails. I have a dead simple form. views -> genalg -> index.html.erb

<h1>Genalg#index</h1>
<p>Find me in app/views/genalg/index.html.erb</p>


  <%= form_with  url: "/calculate" do |form| %>  
  <%= form.text_field :query %>  
  <%= form.submit "calculate" %>
  <% end %>

<% unless @query.nil? %>
  <p><%=@query%></p>
<% end %>

I have a controller under controllers -> genalg_controller.rb

class GenalgController < ApplicationController

  def index
    @query = "biznass"
  end

  def calculate
    puts params
    @query = (params[:query].to_i * 2).to_s
    render :index
  end
end

In routes.rb:

Rails.application.routes.draw do
  get 'genalg/index'
  post '/calculate', to: 'genalg#index' , as: 'index'
 
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

How, when I fill the from text :query and hit submit, can I get the text denoted at the very end of my view to display the value I put in times 2 (per the calculate function)? Seems like it should be easy but clearly I have forgotten some basic tenant of how forms and form submission works.

CodePudding user response:

Change the render to redirect_to and pass params like this

  def calculate
    puts params
    @query = (params[:query].to_i * 2).to_s
    redirect_to index_path(query: @query)
  end

<% unless params[:query].blank? %>
  <p><%=@query%></p>
<% end %>

CodePudding user response:

Looking at your routes file, you are calling index action on submitting a post request for calculate so its always returns @query value from the index method i.e. biznass

If you want to calculate @query using params and use index action for that with same routes defined, you have to update index method

def index
  if params[:query]
    puts params
    @query = (params[:query].to_i * 2).to_s 
  else
   @query = 'biznass'
  end 
    

OR you can change route and controller code

Rails.application.routes.draw do
  get 'genalg/index'
  post '/calculate'
 
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
class GenalgController < ApplicationController

  def index
    @query = params[:query] || "biznass"
  end

  def calculate
    puts params
    @query = (params[:query].to_i * 2).to_s
    redirect_to index_path(query: @query)
  end
end
  • Related