【问题标题】:Changing Rails Model Association from one Model to another将 Rails 模型关联从一个模型更改为另一个模型
【发布时间】: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


【解决方案1】:

基本上你需要在创建项目时设置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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多