问题
I have the following Model with serialized variables:
create_expenses.rb
class CreateExpenses < ActiveRecord::Migration
def change
create_table :expenses do |t|
t.belongs_to :user, index: true
t.string :ref
t.integer :year
t.integer :month
t.text :traject_names, Array
t.text :vehicles_used, Array
t.text :nb_kms, Array
t.text :parkings, Array
t.text :trains, Array
t.text :taxis, Array
t.text :metros, Array
t.text :meals, Array
t.text :hotels, Array
t.text :natures, Array
t.text :amounts, Array
t.text :o_ns, Array
t.text :clients, Array
t.timestamps
end
end
end
expense.rb
class Expense < ActiveRecord::Base
belongs_to :user
serialize :traject_names
serialize :nb_kms
serialize :parkings
serialize :trains
serialize :taxis
serialize :metros
serialize :meals
serialize :hotels
serialize :natures
serialize :amounts
serialize :o_ns
serialize :clients
end
They all look like the same. Example: nb_kms = ["34", "4", "6"]
.
I want to be able to edit all the values. I've tried severals ways but didn't find anything working.
Last thing I've tried is the following:
<%= f.fields_for :nb_kms, @expense.nb_kms[i] do |answer_fields| %>
<%= answer_fields.text_field "", :value => @expense.nb_kms[i] %>
<% end %>
but it doesn't work. Any tips?
回答1:
Found a workaround, not sure if this is optimized though...
For each array, use input
instead of f.text_field:
<input type="number" name="nb_kms[]" value="<%= @nb_kms[i] %>">
Then, in your update
action:
params['nb_kms'].each_with_index do |nb_km, i|
@expense.nb_kms[i] = nb_km
end
if @expense.update(expense_params)
...
I'm currently doing a loop for each array. There's probably a cleaner way to update my arrays but I don't know how (which array should be updated at a given index?)
Finally, since I allow the user to edit the data from the show
View page, I had to add this line in my routes.rb
file:
patch '/expenses/:year/:month/' => 'expenses#update'
I'm open to other solutions.
来源:https://stackoverflow.com/questions/28415176/how-to-edit-a-serialized-array-with-unknown-keys