0

I'm new to Rails and am trying to create a view form_for which adds data in two different models. I've looked at stack overflow posts about multiple models, and I've used a fields_for call to submit the information to the second model. However, my form submission only processes the form_for data, and not the fields_for. Please advise on how I would fix this. My two models are for users and schools (with the goal of someone registering their school and their own information, then being able to log in and attach that school to that adviser)

View code:

<div class="row">
  <div class="col-md-6 col-md-offset-3">
     <%= form_for(@user) do |f| %>

      <%= fields_for(@school, :url => {:controller => "advisers",
                                       :action => "new_school"}) do |s| %>
        ... fields...
      <% end %>
      <legend>Primary Adviser Information</legend>
      ... forms ...
      <%= f.hidden_field :access_level, :value => "Adviser" %>
      <p>&nbsp;</p>
      <div class="col-md-12">
        <%= f.submit "Register", class: "btn btn-primary" %>
      </div>
    <% end %>
  </div>
  </div>
</div>

Advisers Controller:

def new
    @user = User.new
    @school = School.new
  end

  def new_school
    @school = School.new(school_params)
    @school.save
  end

Routes:

 resources :advisers do
    collection do
      post :new_school
    end
  end

Output:

Started POST "/users" for 24.13.7.99 at 2015-07-16 19:41:37 +0000
Processing by UsersController#create as HTML
  Parameters: (params here)
   (0.1ms)  begin transaction
   (inserts user here)
   (17.1ms)  commit transaction
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 6]]
Redirected to https://pennmc2-mdmorant.c9.io/adviser

Notice that it only activates the User post but not the advisers post.

Max Morant
  • 27
  • 5

1 Answers1

0

Use accept_nested_attributes_for inside on of your models - Advisor/User? like this

  accepts_nested_attributes_for :school

Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship

Community
  • 1
  • 1
adamliesko
  • 1,887
  • 1
  • 14
  • 21
  • But school doesn't belong to a particular adviser, since there can be more than one per school, and not all users (admins, among others) belong to a school...? – Max Morant Jul 16 '15 at 23:16