Ruby on rails,将数据保存在两个表中

时间:2016-12-26 02:58:21

标签: ruby-on-rails ruby

我有一个问题。

我有这个型号:

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 %>

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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