2016-12-26 96 views
-1

我有問題。Ruby on rails,將數據保存在兩個表中

我有這樣的模式:

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 

當我創建一個新的項目,我有模型項目的許多屬性和兩個屬性(室和日期)從演示模型,所以我不知道如何將數據從房間和日期屬性發送到演示文稿模型。

所以我的問題是:如何創建一個新的項目,保存項目表和演示文稿表中的數據?

更新#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

你可以嘗試這樣的事情:

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 
+0

在項目控制器中? –

+0

是的,它可以用於創建操作。 – Thanh

+0

好,它現在工作,現在我需要不是靜態xD。我需要插入查看數據 –

相關問題