byroot / activerecord-typedstore

ActiveRecord::Store but with type definition
MIT License
439 stars 57 forks source link

Form helpers does not prefill fields if validation failed #14

Closed Bahanix closed 10 years ago

Bahanix commented 10 years ago
# app/models/transaction.rb
class Transaction < ActiveRecord::Base
  typed_store :invoice, coder: DumbCoder do |s|
    s.string :first_name
  end
end

# app/controllers/transactions_controller.rb
class TransactionsController < ApplicationController
  def create
    @transaction = Transaction.new(transaction_params)
    if @transaction.save
      # ...
    else
      render action: 'new'
    end
  end

  private def transaction_params
    # I tried both :first_name and invoice: [:first_name]
    params.require(:transaction).permit(:first_name, invoice: [:first_name])
  end
end

None of these views prefill text fields if validation failed:

<%= form_for @transaction do |f| %>
  <%= f.label :first_name %>
  <%= f.text_field :first_name %>
<% end %>

<%= form_for @transaction do |f| %>
  <%= f.fields_for :invoice do |i| %>
    <%= i.label :first_name %>
    <%= i.text_field :first_name %>
  <% end %>
<% end %>

It does work with standard attributes.

byroot commented 10 years ago

It's because @transaction.first_name_before_type_cast behave improperly. See https://github.com/rails/rails/blob/a6b9ea2e21ae51f6dfea8cea757ee0ecbebcd87e/actionpack/lib/action_view/helpers/tags/base.rb#L31

I'll fix that tonight.

Thanks!

byroot commented 10 years ago

@Bahanix could you test master to see if it does solve your issue? If yes I'll release a new version.

Bahanix commented 10 years ago

It solves my issue :+1: