我有个问题。
我有这个模型:
class Project < ApplicationRecord
has_many :documents
belongs_to :course_unit
belongs_to :user
has_and_belongs_to_many :people
has_one :presentation
has_and_belongs_to_many :supervisors, :class_name => "Person", :join_table => :projects_supervisors
end
和这个模型:
class Presentation < ApplicationRecord
belongs_to :project
has_and_belongs_to_many :juries, :class_name => "Person", :join_table => :juries_presentations
end
创建新项目时,我具有模型Project的许多属性以及Presentation模型的两个属性(房间和日期),因此我不知道如何将房间和日期属性中的数据发送到表示模型。
所以我的问题是:如何创建一个新项目,将数据保存在项目表和演示文稿表中?
更新#1
我的项目负责人:
def new
@project = Project.new
end
def edit
end
def create
@project = Project.new(project_params)
@project.build_presentation
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, notice: 'Project was successfully updated.'}
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
private
def set_project
@project = Project.find(params[:id])
end
def project_params
params.require(:project).permit(:title, :resume, :github, :grade, :project_url, :date, :featured, :finished, :user_id, :course_unit_id, presentation_attributes: [ :date , :room ])
end
我对项目的索引视图是:
<%= form_for @project do |f| %>
<%= f.fields_for :presentations do |ff| %>
<%= ff.label :"Dia de Apresentação" %>
<%= ff.date_field :date %>
<%= ff.label :"Sala de Apresentação" %>
<%= ff.text_area :room %>
<% end
<%= f.submit %>
<% end %>
您可以尝试如下操作:
project = Project.new(name: 'project 1')
project.build_presentation(room: 'room 1', date: Time.current)
project.save
它将保存项目名称project 1
和演示文稿属于该项目,房间room 1
和日期为Time.current
。
而且,您需要更新模型以避免进行状态验证。
class Project < ApplicationRecord
has_one :presentation, inverse_of: :project
end
class Presentation < ApplicationRecord
belongs_to :project, inverse_of: :presentation
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句