1

I recently tried adding an Array type column in my Rails app which uses Postgres 9.3. I followed some online tutorials and added the following code into my project.

Migration

add_column :matches, :p1_characters, :string, array: true, default: []
add_column :matches, :p2_characters, :string, array: true, default: []

Now if I try to manually update a match's characters in the console like so:

> m = Match.first
> m.p1_characters = ["1","2","3"]
> m.save
# Works fine!

Everything saves correctly in the database as expected.

The problem lies in trying to update the p1_characters/p2_characters attributes in my rails app.

p1_edit_character_.html.erb

<%= simple_form_for(@match, method: :patch,
                           :url => p1_set_character_match_path(@match)) do |f| %>

# displays a form of check boxes where the user can select multiple characters.

  <h1>Select P1 Character</h1>
  <%= f.input :p1_characters, label: "Player 1 Character", as: :check_boxes, 
                              collection: @characters %>
  <%= f.button :submit, "Select Character", class: "btn-lg btn-primary" %>
<% end %>

I know that the params being passed to my controller is:

"match"=>{"p1_characters"=>["1", "2", "3", ""]}

The error I get is

undefined method `gsub' for 1:Fixnum

Below is my controller with the relevant methods and strong params matches_controller.rb

def p1_edit_character
  @match = Match.find(params[:id])
  @characters = Game.find(@match.game_id).characters
end

def p1_set_character
  @match = Match.find(params[:id])
  if @match.update_attributes(match_params)
    if @match.p1_characters != []
    flash[:notice] = "P1 character set."
  end
    redirect_to matches_path
  end
end

private
  def match_params
    params.require(:match).permit(:p1_score, :p2_score, :match_date, 
    :p1_accepted, :p2_accepted, {p1_characters: []}, {p2_characters: []},
    :disputed, :finalized_date)
  end

Please, any guidance would be so helpful.

Thanks.

  • Hi. Passing an array as a strong parameter may be messing you up. As per [this post](http://stackoverflow.com/questions/16549382/how-to-permit-an-array-with-strong-parameters), in `match_params`, explicitly make :p1_caracters an array as in `params.require(:match).permit(:p1_score, :p2_score, :match_date, :p1_accepted, :p2_accepted, :p1_characters => [], :p2_characters)` – BenU Mar 11 '14 at 02:03
  • Hey BenU, I've run into a new error now. I added {p1_characters: []} into my strong parameters but now I get this error: undefined method `gsub' for 44:Fixnum – Victor Tran Mar 11 '14 at 02:19
  • You're getting closer. Have you tried googling your new error message? There seems to be a number of posts with insight into your new one. GTEM. – BenU Mar 15 '14 at 14:53
  • It's a rails bug https://github.com/rails/rails/issues/13444 – Alexander Balashov Jul 04 '17 at 13:39

0 Answers0