我有两个模型,用户和组织,它们使用分配表具有 has_many 关系。创建用户时我有一个嵌套的资源表单,它可以很好地创建一个关联的组织。但是,在创建组织时,它不会将其与用户相关联。
这是我的相关组织控制器代码:
def new
@organization = current_user.organizations.build
end
def create
@organization = current_user.organizations.build(params[:organization])
@organization.save
end
还有我的模型:
组织分配
class OrganizationAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :organization
attr_accessible :user_id, :organization_id
end
组织:
class Organization < ActiveRecord::Base
validates :subdomain, :presence => true, :uniqueness => true
has_many :organization_assignments
has_many :people
has_many :users, :through => :organization_assignments
attr_accessible :name, :subdomain
end
用户:
class User < ActiveRecord::Base
has_many :organization_assignments
has_many :organizations, :through => :organization_assignments
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
accepts_nested_attributes_for :organizations
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :organizations_attributes
# attr_accessible :title, :body
end
表单视图:
= form_for @organization, :html => { :class => 'form-horizontal' } do |f|
- @organization.errors.full_messages.each do |msg|
.alert.alert-error
%h3
= pluralize(@organization.errors.count, 'error')
prohibited this user from being saved:
%ul
%li
= msg
= f.label :name
= f.text_field :name
= f.label :subdomain
= f.text_field :subdomain
.form-actions
= f.submit nil, :class => 'btn btn-primary'
= link_to t('.cancel', :default => t("helpers.links.cancel")), organizations_path, :class => 'btn'
事后我可以在控制台中很好地关联组织,所以我很确定模型中的关系设置正确。还有什么我想念的吗?