ruby on rails - Using form_for with "becomes" loses child association -
when building out form handles sti, if use becomes
transform object parent class, lose ability use nested fields it.
i have 2 models
class login < activerecord::base belongs_to :user end class user < activerecord::base has_one :login accepts_nested_attributes_for :login end
i have few subclasses of user.
class consumer < user end class admin < user end class agent < user end
initially had problems routing, since rails assume wanted route specific current class rather parent class, used @user.becomes(user)
, apparently way handle that. part works fine, causes @user.login
disappear.
controller
class admin::userscontroller < admincontroller load_and_authorize_resource before_filter :authenticate_user! def index render 'index' end def new @user = user.new @user.build_login render 'new' end def create @user = user.new(user_params) if @user.save flash[:notice] = "account confirmation instructions sent #{@user.login.email}" redirect_to new_user_path else flash.now[:error] = @user.errors.full_messages.to_sentence # @ point, can confirm @user.login still exists... render 'new' end end private def user_params params.require(:user).permit( :type, :dealership_id, login_attributes: [ :email ]) end end
here's relevant form view bit
<%= simple_form_for(@user.becomes(user), html: {class: "user-form"}) |f| %> <%= f.simple_fields_for :login |l| %> <div class="field"> <%= l.label :email %><br /> <%= l.email_field :email %> </div> <% end %> <div class="field"> <%= f.label :type %> <%= f.select :type, options_for_select(current_user.types_can_create), include_blank: "- select -", class: "form-control", id: "select_type" %> </div> <div class="actions"> <%= f.submit "register" %> </div> <% end %>
the text field :email
doesn't display because @user.login
nil
. expected behavior when using becomes
?
having used becomes
once before, can attest scant experience -- whenever use it, invokes new instance of class.
i'm not sure specifics, bottom line surmise @user.becomes(user)
overriding @user.build_login
...
returns instance of specified klass attributes of current record.
--
in case, set path explicitly (as you're using user
anyway):
<%= simple_form_for @user, url: user_path, method: :post html: {class: "user-form"} |f| %>
Comments
Post a Comment