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.