我在通過organization_id將項目模型關聯到組織模型時遇到問題。我開始將項目模型與用戶模型相關聯,但後來我改變主意並決定將每個創建的項目與創建該項目的組織關聯起來。將導軌模型關聯從一個模型更改爲另一個
因此,通過遷移,我插入了一個新列以將organization_id插入到項目模型中。問題是,無論何時我創建一個新項目(以組織身份登錄),organization_id仍爲「無」。我做錯了這個協會不工作?
這是遷移文件:下面
class AddOrganizationIdToProjects < ActiveRecord::Migration
def change
\t add_column :projects, :organization_id, :integer, index: true
end
end
您可以檢查出項目模型和組織模式,具有相應的模式(通過註釋寶石)。
工程模型(用模式)
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# name :string
# short_description :text
# description :text
# image_url :string
# status :string default("pending")
# goal :decimal(8, 2)
# expiration_date :date
# created_at :datetime not null
# updated_at :datetime not null
# organization_id :integer
# start_date :date
#
class Project < ActiveRecord::Base
\t belongs_to :organization
end
組織模式(與模式)
# == Schema Information
#
# Table name: organizations
#
# id :integer not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string
# last_sign_in_ip :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Organization < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :projects, dependent: :destroy
end
編輯:添加ING項目控制器創建操作的要求:
\t def create
\t \t @project = Project.new(project_params)
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
感謝您的幫助!
你說的organization_ID始終是零。但你如何/在哪裏設置它? – rdupz
你是如何創建項目模型的?請顯示項目控制器創建操作。 – SacWebDeveloper
@SacWebDeveloper根據要求,項目控制器創建操作已啓動。謝謝! – mmgrillo