我有两个模型,用户和组织,它们使用赋值表具有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'
我能够在控制台中将组织关联起来很好,所以我很确定在模型中正确设置了关系。还有什么我想念的吗?