【问题标题】:Rails: Nested Attributes & Model?Rails:嵌套属性和模型?
【发布时间】: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


    【解决方案1】:

    我将创建第四个模型,称为 UserOrganization,它具有以下属性: user_idorganization_idrole_id。在 UserOrganization 模型中,我将拥有以下内容:

    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 =&gt; :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

    【讨论】:

    • 我添加了我的代码并且收到了一个错误。如果您有时间并且可以评论,我将真诚地感谢它。再次感谢。
    • 我明白了。感谢您帮助我找到正确的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2015-07-10
    相关资源
    最近更新 更多