在我的应用程序中,我有3个型号:
在控制器中我这么写:
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
答案 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