我正在构建一个执行以下操作的Rails应用程序:用户可以创建一个新项目,并且在每个Project中可以创建不同的Papers。
我正在从外层开始构建它(这意味着,我首先希望能够在开始对Papers部分进行编码之前创建,更新,删除一个项目)。
我遇到以下问题:我为project_controllers
编写了新代码并创建了动作,但是未保存新实体。 (它不会显示在index.html.erb
中,并且_form.html.erb
仍在渲染,这意味着它没有保存)
我认为问题是项目has_many
的论文,并且由于我尚未对Paper部分进行编码,因此会产生问题。但是我不确定这是否是正确的答案。
project.rb
class Project < ApplicationRecord
has_many :papers, dependent: :destroy
belongs_to :user
end
project_controller.rb
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
def index
@projects = Project.all
end
def show
end
def new
@project = Project.new
end
def create
@project = Project.new(project_params)
@project.save
if @project.save
redirect_to projects_path()
else
render :new
end
end
def edit
end
def update
@project.update(project_params)
redirect_to project_path(@project)
end
def destroy
@project.destroy
redirect_to projects_path
end
private
def project_params
params.require(:project).permit(:title, :body)
end
def set_project
@project = Project.find(params[:id])
end
end
new.html.erb
<%= render 'form', project: @project %>
_form.html.erb
<div class="container">
<div class="row ">
<div class="col-sm-4 col-sm-offset-4">
<%= form_for(@project) do |f| %>
<div class="form-group">
<%= f.label :title, "Title of the Project"%>
<%= f.text_field :title, as: :string, class: 'form-control'%>
</div>
<div class="form-group">
<%= f.label :body, "Description of the Project"%>
<%= f.text_area :body, rows: 20, class: 'form-control' %>
</div>
<%= f.submit "Confirm", class:"btn btn-secondary btn-lg" %>
<% end %>
</div>
</div>
</div>