【发布时间】:2016-03-08 15:08:28
【问题描述】:
我无法通过 organization_id 将项目模型与组织模型相关联。我开始将项目模型与用户模型相关联,但后来我改变主意并决定将创建的每个项目与创建它的组织相关联。
因此,通过迁移,我插入了一个新列,将一个 organization_id 插入到项目模型中。问题是,每当我创建一个新项目(作为组织登录)时,组织 ID 仍然是“nil”。我做错了什么,协会不起作用?
这是迁移文件:
class AddOrganizationIdToProjects < ActiveRecord::Migration
def change
add_column :projects, :organization_id, :integer, index: true
end
end
您可以查看项目模型和组织模型,以及下面的相应架构(通过注释 gem)。
项目模型(带架构)
# == 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
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
已编辑:根据要求添加项目控制器创建操作:
def create
@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 总是nil。但是你如何/在哪里设置它?
-
您是如何创建项目模型的?请显示项目控制器创建操作。
-
@SacWebDeveloper 根据要求,项目控制器创建操作已启动。谢谢!
-
@mmgrillo 好吧,成功了吗?
标签: ruby-on-rails ruby model-associations