Getting from controller to associated model

55 views Asked by At

I can't get along with saving Students with one POST when i"m saving Project.

My Projects controller looks like:

class ProjectsController < ApplicationController

  def index
    @projects = Project.all
  end

  def new
    @project = Project.new
    3.times do
      student = @project.students.build
    end
  end

  def create
    @project = Project.new(project_params)
    @project.status = "Waiting"
    # I'm not sure about these lines
    @project.students.each do |student|
      student = Student.new(params[:name])
    end
    @project.save!
    redirect_to projects_path
  end

  private
    def project_params
      params.require(:project).permit(:name, :lecturer)
    end

end

And a new_project view looks like:

<h1>Creating new project...</h1>

<%= form_for @project, url: projects_path do |f| %>
  <p>
    <%= f.label :name %>
    <%= f.text_field :name %>
  </p>

  <p>
    <%= f.label :lecturer %>
    <%= f.text_field :lecturer %>
  </p>

    <p>
        <%= f.fields_for :students do |s| %>
            <%= s.label :name %>
            <%= s.text_field :name %>
        <% end %>
    </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

And my question is how to save Project and Students (assigned to it) using one form?

1

There are 1 answers

0
randompawn On BEST ANSWER

First, your project_params method isn't allowing the students' names to be submitted. Try something like this:

def project_params
  params.require(:project).permit(:name, :lecturer, students_attributes: [ :name ] )
end

Next, in your Project model you'll need the line

accepts_nested_attributes_for :students

(You might have put it there already - but if you didn't, you'll need to.)

Now that that's done, you shouldn't need these lines in your Project#create method:

@project.students.each do |student|
  student = Student.new(params[:name])
end

Because your project can now accept nested attributes for students, they should be created automatically with the project when you save it.