作为RoR新手,我非常感谢任何/所有提前提供的帮助! 在尝试创建以下所需的模型时,我感到困惑。
我有 3 个对象:用户、组织和角色。用户可以属于一个或多个组织,但每个组织只有 1 个角色。 例如:
乔恩 |组织1 |所有者
乔恩 |组织2 |员工
鲍勃 |组织1 |员工
鲍勃 |组织2 |所有者
我将如何在我的模型中设置它(has_many,通过 =>?(,并且当我有一个编辑表单时,我能够在同一表单中更新用户信息、他们的组织和角色?注意:不确定是否相关,但我只打算允许那些所有者编辑他们的组织。
再次感谢!
编辑以下是我得到的,加上我现在收到的错误:
models/user.rb
class User < ActiveRecord::Base
has_many :org_roles
has_many :orgs, :through => :org_roles
accepts_nested_attributes_for :orgs, :allow_destroy => true
has_one :user_detail
has_one :user_address
attr_accessible :orgs
end
models/org.rb
class Org < ActiveRecord::Base
end
models/role.rb
class Role < ActiveRecord::Base
end
型号/org_role.rb
class OrgRole < ActiveRecord::Base
belongs_to :user
belongs_to :org
belongs_to :role
validates_presence_of :user, :org, :role
validates_uniqueness_of :org_id, :scope => :user_id
end
views/edit.html.erb
#user form info above...
<%=f.fields_for :orgs do |ff| %>
<div>Your Organization Name:<br />
<%= ff.text_field :name%></div>
<% end %>
错误信息:
Can't mass-assign protected attributes: orgs_attributes
解决:
添加了 :orgs_attributes 到我的用户模型,attr_accessible
我将创建一个名为UserOrganization的第四个模型,它具有以下属性: user_id
,organization_id
和role_id
。在用户组织模型中,我将具有以下内容:
class UserOrganization < ActiveRecord::Base
belongs_to :user
belongs_to :organization
belongs_to :role
validates_presence_of :user, :organization, :role
validates_uniqueness_of :organization_id, :scope => :user_id
end
我们所拥有的内容将满足您的标准,即用户能够属于许多组织,但每个组织最多只能属于一次,并且对于每个关联,他们都必须具有角色。
用户、组织和角色的关联应该相当直接地实现(用户有许多用户组织(。如果你想通过用户模型直接获得组织,你也可以有has_many :organizations, :through => :user_organizations
。
另外,对于您关于编辑表单的问题,我建议您阅读有关accepts_nested_attributes_for
:
http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for
和
http://railscasts.com/episodes/196-nested-model-form-part-1