【发布时间】:2012-02-27 02:22:02
【问题描述】:
作为一名 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
models/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
【问题讨论】:
标签: ruby-on-rails model nested-attributes