How to display error messages in a multi-model form with transaction?

后端 未结 5 1333
长情又很酷
长情又很酷 2021-01-23 06:53

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The p

5条回答
  •  臣服心动
    2021-01-23 07:29

    organization has_many :users and user belongs_to :organization

    organization.rb

    accepts_nested_attributes_for :users
    

    new.html.erb

    <%= form_for @organization, url: next_url do |f| %>
     <%= render 'shared/error_messages', object: @organization %>
     <%= f.text_field :name %>
        # Other fields
     <%= f.fields_for(:users,@organization.users.build) do |p| %>
       <%= p.email_field :email %>
       # Other fields
     <% end %>
     <%= f.submit "Submit" %>
    <% end %>
    

    In controller

    def create
      @organization = Organization.new(new_params)
      if @organization.save
        flash[:success] = "Yeah!"
        redirect_to root_url
      else
       render :new
      end
    end
    

提交回复
热议问题