Simon
Simon

Reputation: 629

Save in DB js-generated field in Rails

So I have a form in Rails, very basic. But I decided to add some features. Little bit of context.
You choose either you're a man or a woman, and then the form generate some field. I had a field that was already existing in the V1, but when I generate it with javascript, it's not saved in DB. I don't really understand why. Here are some code.

Controller

def create
  @pokemon = Pokemon.new(params[:pokefuck])

  respond_to do |format|
    if @pokemon.save
      format.html { redirect_to '/pokemons', notice: 'pokemon was successfully created.' }
      format.json { render json: @pokemon, status: :created, location: @pokemon }
    else
      format.html { render action: "new" }
      format.json { render json: @pokemon.errors, status: :unprocessable_entity }
    end
  end
end

View

Original field that works

<%= f.select "size", options_for_select(size, @pokemon.size) %>

size is a hash

Created one, that does not work

var s = document.createElement("select");
s.name = "po";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.po.options[i] = new Option(size[i], size[i]);
}

I supposed it was because the name of my new element wasn't pokemon[size], but when I used this, the line document.formName.pokemon[size].options[i] didn't work anymore.

So I'm kinda struggling to see how I can make this works. Thanks!

Upvotes: 0

Views: 173

Answers (2)

jemminger
jemminger

Reputation: 5173

Assuming from your controller code that your form fields are namespaced into "pokefuck", then you'll need to make the name of your select "pokefuck[size]", and then reference that name in the form's elements collection:

var s = document.createElement("select");
s.name = "pokefuck[size]";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.elements['pokefuck[size]'].options[i] = new Option(size[i], size[i]);
}

Upvotes: 1

Daniel Westendorf
Daniel Westendorf

Reputation: 3465

The name of the field needs to put it into the params hash for you your pokefuck.

pokefuck[size] should be the name of the form element. Append the form element to the form element you're submitting.

Upvotes: 1

Related Questions