0

I have a Devise "edit user" form in my Rails app. A User also contains a school_id. On my edit user form I have a section that shows what school the user is subscribed to. Next to the School name I have a button that sets the User's school_id to nil. However, since this is actually a form with a hidden field, the user can "Save changes" on the edit user form and it will set the school_id to nil because of the other form I have on the page.

Pseudo code:

edit user information
School: schoolname [button to remove school]
edit more user information
[Submit changes]

Button to remove school:

<% if current_user.school %>School: <b><%=link_to current_user.school.name, current_user.school %></b> 
   <%= form_for(@user) do |f| %>
      <%= f.hidden_field(:school_id, :value => nil) %>               
      <%= f.submit "Remove school", class: "btn btn-danger btn-small" %>
   <% end %>

Is there a way to achieve this without having to move the the Remove School button outside the form? It fits very nicely in the workflow but it causes issues since its now technically part of the edit devise user registration form. Any ideas?

Thanks!!

usha
  • 28,973
  • 5
  • 72
  • 93
winston
  • 3,000
  • 11
  • 44
  • 75
  • You can have a look at this article http://weblog.rubyonrails.org/2009/1/26/nested-model-forms/ – Rinku Feb 10 '14 at 08:59
  • Would nested forms work here, even though I'm still only updating one model? I'm only updating the User model with both forms. – winston Feb 10 '14 at 11:15
  • 1
    You should not nest forms - http://stackoverflow.com/questions/379610/can-you-nest-html-forms – bridiver Feb 10 '14 at 13:21

1 Answers1

1

You can achieve it with action in the controller.

For example In view:

<%= link_to 'Remove school', user_path(@current_user), :method => :delete, :class => "btn btn-danger btn-small" %>

In controller:

def destroy
    @current_user.update_attribute(:value, nil)
    respond_to do |format|
      format.html{redirect_to :back}
    end
end
BinaryMee
  • 2,102
  • 5
  • 27
  • 46