Rails模型.build设置id

时间:2014-04-09 18:54:07

标签: ruby-on-rails ruby ruby-on-rails-4 activemodel

在我的应用程序中,我有3个型号:

  • OrganizationType
  • 组织
  • OrganizationTypeLink 如你所知:我的组织可以执行多项操作,而这种类型的操作我想与组织联系......

在控制器中我这么写:

def create
    @admin_organization = Organization.new(admin_organization_params)
@admin_organization.organization_type_links.build(organization_type_id: params[:organization_type_id], organization_id: @admin_organization.id)
if @admin_organization.save
....

在模型OrganizationTypeLink中,我在db中看到了新行,但是如何在Organization organization_type_link_id中存储?我怎么能把它存储在数据库中?

我是RoR的新手,所以请提供建议)

UPD:

class Organization < ActiveRecord::Base
  belongs_to :organization_type
  has_many :organization_type_links, :dependent => :destroy
end

class OrganizationTypeLink < ActiveRecord::Base
  belongs_to :organization
  belongs_to :organization_type
end

class OrganizationType < ActiveRecord::Base
  has_many :organizations
  has_many :organization_type_links
end

1 个答案:

答案 0 :(得分:1)

  

如何在Organization_type_link_id中存储?我怎么能把它存放在db?

您目前在这3个模型中定义关联的方式:OrganizationType, Organization and OrganizationTypeLink

Organization has_many organization_type_links表示OrganizationTypeLink将在其中包含名为organization_id的外键,而不是相反。

如果您想在组织中拥有organization_type_link_id,则需要将关联设置为:

class Organization < ActiveRecord::Base
  belongs_to :organization_type
  belong_to :organization_type_link
end

class OrganizationTypeLink < ActiveRecord::Base
  has_many :organizations, :dependent => :destroy
  belongs_to :organization_type
end