我在通过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