I have two models each with their own resources: Organizations and Members. An organization has multiple members and a member is only a member to one organization.
How can I create a simple nested form that signs up a new organization as well as one member for that organization?
My current attempt is below. On submitting the form, this however generates the error message
unknown attribute ‘org_name’ for Member
``
, which I don’t get especially since org_name is a column within the Organization model and not the Member model.
Organization model
has_many :members, dependent: :destroy
accepts_nested_attributes_for :members, :reject_if => :all_blank, :allow_destroy => true
**Member model**
belongs_to :organization
Organizations controller
def new @organization = Organization.new @member = @organization.members.build end
def create @organization = Organization.new(organizationnew_params) @member = @organization.members.build(organizationnew_params) if @organization.save && @member.save @member.send_activation_email #Will Rails be able to get to this method? The send_activation_email method exists in multiple models and Rails should here use the version from the Member model. flash[:success] = “Please check your email to activate your account.” redirect_to root_url else render ‘new’ end end
def organizationnew_params params.require(:organization).permit(:org_name, :phone, member_attributes: [:email, :username, :admin, :password, :password_confirmation ]) end
Organizations new view
<%= form_for(@organization) do |f| %> <%= f.text_field :org_name, %> <%= f.text_field :phone %>
<%= f.fields_for :member do |p| %> <%= p.text_field :username %> <%= p.email_field :email %> <%= p.password_field :password %> <%= p.password_field :password_confirmation %> <%= hidden_field_tag :admin, true %> <% end %>
<%= f.submit “Sign up”, class: “formbutton btn btn-default” %> <% end %>
What am I doing wrong? How can I create a simple nested form?