LuisZuluaga
LuisZuluaga

Reputation: 155

How can I update a controller variable using button in the html in ruby on rails?

I want to update a variable of my home controller everytime someone clicks on a button. Right now my button does a post method where I think the variable is updated but in the html is not showing.

My routes:

Rails.application.routes.draw do
  get 'home/index'
  get 'home/plays'
  get 'home/analyze'
  post 'home/analyze' => 'home#get_lines'
  root 'home#index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Here is my code:

class HomeController < ApplicationController
  @numberOfLines = 0

  def index
  end

  def plays
    @plays = PlaysList.new.get.list
  end

  def analyze
    @playStats = PlayAnalyzer.new(HttpSource.new(params[:playLink]))
    @playName = params[:playName]
    @playLink = params[:playLink]
    @characters = @playStats.characters
    @numberOfCharacters = @characters.length
  end

  def get_lines
    @numberOfLines = 10
  end

end

And in my html:

<h3> Analyzing the play <%= @playName %> </h3>
<p> Number of characters in the play: <%= @numberOfCharacters %> </p>

<p> Look how many lines said a character: </p>
<select id="people" name="people">
    <% @characters.each do |character| %>
        <option value=<%= character %>> <%= character %> </option>
    <% end %>
</select>

<p> Number of lines in the play: <%= @numberOfLines %> </p>
<%= button_to 'Get lines', home_analyze_path , method: 'post'  %>

numberOfLines is the variable I want to update everytime someone clicks a button

Upvotes: 1

Views: 478

Answers (1)

rewritten
rewritten

Reputation: 16435

The controller is not stateful, once it has rendered a page it dies, and a new request will get a new instance (with completely new instance variables).

To keep state (per session) you can use the session (so read and write to the session) and re-render the whole page (or the corresponding piece if you are using turbo).

To keep global state (so separate sessions increase the same count) you need to use Redis and actioncable. Broadcast the change and let the browser react (ny retrieving a new piece of HTML, or just by updating what's in the current document.

Upvotes: 1

Related Questions