将Rails模型关联从一个模型更改为另一个模型

时间:2016-03-08 15:08:28

标签: ruby-on-rails ruby model-associations

我无法通过organization_id将项目模型与组织模型相关联。我开始将项目模型与用户模型相关联,但后来我改变主意并决定将创建的每个项目与创建它的组织相关联。

因此,通过迁移,我插入了一个新列,将organization_id插入到项目模型中。问题是每当我创建一个新项目(以组织形式登录)时,organization_id仍然是“无”。如果协会无效,我做错了什么?

这是迁移文件:

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

基本上你需要在创建项目时设置organization ID,它不会自动知道。如下所示应该这样做,这将在您的projects_controller.rb文件中完成:

class ProjectsController < ApplicationsController
   def create
      current_organization = Organization.find() #the org id thats logged in
      Project.create(organization: current_organization)
      redirect_to #somewhere
   end
end

答案 1 :(得分:0)

使用组织的关联方法创建项目,它会自动添加organization_id。以下代码假定您在current_user上找到所需的组织ID。

def create
  organization = Organization.find(current_user.organization.id)
  @project = organization.project.build(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

http://guides.rubyonrails.org/association_basics.html#detailed-association-reference