refactor simple_form form radio-button field

32 Views Asked by At

I have a User model which renders a form patrial (using simple_form) for new & edit actions and here's the content of it:

<div>
  <%= simple_form_for @user do |f| %>
    <%= f.error_notification %>
    <%= f.input :its %>
    <%= f.input :name %>
    <% if action_name == "edit" %>
      <%= f.input :apartment, collection: collection_of(User.apartments), as: :radio_buttons %>
    <% else %>
      <%= f.input :apartment, input_html: {checked: false}, collection: collection_of(User.apartments), as: :radio_buttons %>
    <% end %>
    <%= f.input :flat_no %>
    <%= f.input :mobile %>
    <%= f.input :email %>
    <%= f.button :submit %>
  <% end %>
</div>

The radio-button field is similar for both actions but with a difference that I don't want the value in the field to be pre-selected in the new action. This happens because I have set the default: at the database level which automatically selects that value. A checked HTML attribute in the form checks that particular value in the menu. To uncheck it, the attribute checked: must be set to false or removed.

I want to define the radio-button field once regardless of what action it is at. If the action_name == new, it must be unchecked and checked otherwise. So, how can I refactor this field?

I have tried doing this:

<%= f.input :apartment, collection: collection_of(Sabeel.apartments), as: :radio_buttons, input_html: {checked: action_name == "edit"} %>

But this checks the wrong value of the radio button field in the edit form. It checks the last value in the form. This happens because all the checked attribute in HTML is set to value checked and since radio-button types can only be checked by one value, the last value is being checked. But for the new action the checked attribute is not being set hence no values are being selected by default.

Any other ideas are welcome too! Thanks!

1

There are 1 best solutions below

0
smathy On

I'd just do it in your controller when you create your @user:

def new
  @user = User.new apartment: nil
end