Rails Nested Forms with belongs_to


/ Published in: Ruby
Save to your folder(s)

Easy way to add belongs_to association to nested forms in Rails


Copy this code and paste it in your HTML
  1. # user.rb
  2.  
  3. class User < ActiveRecord::Base
  4. belongs_to :address
  5. accepts_nested_attributes_for :address # can't have allow_destroy
  6. end
  7.  
  8. # users_controller.rb
  9.  
  10. class UsersController < ApplicationController
  11. resource_controller
  12. before_filter :load_object, :except => :index
  13.  
  14. # called at the beginning of each action
  15. def load_object
  16. @user = User.find(...)
  17. @user.address ||= Address.new()
  18. @user
  19. end
  20. end
  21.  
  22. # users/edit.html.erb
  23.  
  24. <% form_for(@user, :url => collection_url) do |f| %>
  25. <%= render :partial => "form", :locals => { :f => f } %>
  26. <p>
  27. <%= submit_tag t("create"), {"class" => "wymupdate"}%>
  28. </p>
  29. <% end %>
  30.  
  31. # users/_form.html.erb
  32.  
  33. <table class="admin-report" width="545">
  34. <fieldset id='name'>
  35. <div class="inner">
  36. <p class="field">&nbsp;</p>
  37. <p id="aname" class="field">
  38. <%= f.label :name, t(:name) %><br />
  39. <%= f.text_field :name, :class => 'required' -%><span class="req">*</span>
  40. </p>
  41. </div>
  42. </fieldset>
  43. <%= render :partial => "address_form", :locals => { :f => f } %>
  44. </table>
  45.  
  46. # users/_address_form.html.erb
  47.  
  48. <fieldset id='address'>
  49. <% f.fields_for :address do |address_form| %>
  50. <legend><%= t("address")%></legend>
  51. <div class="inner">
  52. <p class="field">&nbsp;</p>
  53. <p id="afname" class="field">
  54. <%= address_form.label :firstname, t(:first_name) %><br />
  55. <%= address_form.text_field :firstname, :class => 'required' -%><span class="req">*</span>
  56. </p>
  57. </div>
  58. <% end %>
  59. </fieldset>

URL: rails-accepts-nested-attributes-for-belongs-to

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.