Can't create form_for associated models

430 views Asked by At

I'm writing a simple web application which I like to call PMS (Projects Management System). It this app I have 2 models Projects and Students. I have set (I guess... cuz I'm a newbie) association between these two models. Projects has many students but student belongs to one project (Maybe it'll change with time).

But my problem is in getting everything work together. I don't know how I can insert new students inside new project form. I've tried everything and still nothing!

Here are my source files:

Projects controller:

class ProjectsController < ApplicationController
  def show
    @projects = Project.all
  end

  def create
    @project = Project.new(project_params)
    @project.status = "Waiting"
    @project.save
    redirect_to root_path
  end

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

Students Controller:

class StudentsController < ApplicationController
  def create
    @project = Project.find(params[:project_id])
    @student = @project.students.create(params[:student])
    @student.save
  end
end

Models:

class Project < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :project
end

View:

Add new project

<%= form_for :project, url: projects_path do |f| %>
    <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :lecturer %>
        <%= f.text_field :lecturer %>
    </p>
        <%= form_for([@project, @project.students.build]) do |s| %>
          <p>
            <%= s.label :name %><br />
            <%= s.text_field :name %>
          </p>
        <% end %>
    <p>
        <%= f.submit %>
    </p>
<% end %>

Routes:

RoRPMS::Application.routes.draw do
  # You can have the root of your site routed with "root"
  root 'projects#show'

  resources :projects do
    resources :students
  end
end
1

There are 1 answers

1
jbmyid On

You can use "nested_form" to create project with students as well

<%= nested_form_for @project do |f| %>
    <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :lecturer %>
        <%= f.text_field :lecturer %>
    </p>
        <%= fields_for :students do |s| %>
          <p>
            <%= s.label :name %><br />
            <%= s.text_field :name %>
          </p>
        <% end %>
        <%= f.link_to_add "Add new student", :students %>
    <p>
        <%= f.submit %>
    </p>
<% end %>

In Project Model add

accepts_nested_attributes_for :students