Home > Software design >  Rails MVC - How to pass a randomly generated array to the next page with the same elements
Rails MVC - How to pass a randomly generated array to the next page with the same elements

Time:06-30

I'm creating a TextTwist like game.

def initialize
  super
  @letters = ('a'..'z').to_a.sample(10)
end

def game
  # @letters = ('a'..'z').to_a.sample(10)
end
  
def results
  #How to display letters
end

So in my game page, I display an array of random letters which I declared in the game method of my controller. The problem is, in my results page, where I return back the same array of random letters and reveal if user was able to create a word from the random letters. I need to display those same array of random letters. I tried declaring them in initialize, but when I called them on my results page it displayed a different set of random letters.

In my HTML page, I use <%=letters> to display the array. And then a form for them to type the word. When they submit, user goes to the results page. Is there a way for me to pass <%=letters> to the next page and be displayed?

CodePudding user response:

I think you can solve this problem with rails session feature. You can store the letters that generated in game action to the session and then when the user submit the form then you can get that previously generated letter array from session. Here is the code example for this:

def game
  @letters = ('a'..'z').to_a.sample(10)
  session[:letters] = @letters
end

def result
  @letters = session[:letters]
end

CodePudding user response:

One option would be to add a hidden_field_tag to your form and store the serialized value of @letters in that field.

<%= hidden_field_tag :letters, @letters.join(',') %>

The value of that field will then be passed to the controller again when the form is submitted. In the controller, you can then read the letters from the params:

@letters = params[:letters].split(',')

Another option might be making the Game a ActiveRecord model and storing the random letters for a specific game in the database.

  • Related