Ruby on rails Can';t为关联模型创建表单_
我正在编写一个简单的web应用程序,我喜欢称之为PMS(项目管理系统)。在这个应用程序中,我有两个模型项目和学生。我已经在这两个模型之间建立了关联(我猜…因为我是新手)。项目有很多学生,但学生属于一个项目(可能会随着时间而改变) 但我的问题是把所有的事情都安排在一起。我不知道如何在新的项目表格中插入新的学生。我什么都试过了,还是一无所获 以下是我的源文件: 项目控制员:Ruby on rails Can';t为关联模型创建表单_,ruby-on-rails,associations,form-for,nested-form-for,Ruby On Rails,Associations,Form For,Nested Form For,我正在编写一个简单的web应用程序,我喜欢称之为PMS(项目管理系统)。在这个应用程序中,我有两个模型项目和学生。我已经在这两个模型之间建立了关联(我猜…因为我是新手)。项目有很多学生,但学生属于一个项目(可能会随着时间而改变) 但我的问题是把所有的事情都安排在一起。我不知道如何在新的项目表格中插入新的学生。我什么都试过了,还是一无所获 以下是我的源文件: 项目控制员: class ProjectsController < ApplicationController def show
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
class StudentsController < ApplicationController
def create
@project = Project.find(params[:project_id])
@student = @project.students.create(params[:student])
@student.save
end
end
class Project < ActiveRecord::Base
has_many :students
end
class Student < ActiveRecord::Base
belongs_to :project
end
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
您也可以使用“嵌套表单”与学生一起创建项目
<%= 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 %>
使用
保存
时,必须检查布尔结果。您可以尝试使用save
而不是保存
,如果对象无法保存,它将引发异常,指示错误。好的,我明白了,但这仍然不是我要解决的问题…你是否在gem文件中添加了“嵌套表单”gem如果是,那么你会得到什么错误?
<%= 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 %>
accepts_nested_attributes_for :students