Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: Nested Attributes & Model?
    text
    copied!<p>As an RoR newbie, I greatly appreciate any/all assistance in advance! I'm confusing myself when attempting to create the models needed for the following. </p> <p>I have 3 objects: Users, Organizations and Roles. Users can belong to one or more Organizations, but will have only 1 role per organization. For example:</p> <p>Jon | Org1 | Owner</p> <p>Jon | Org2 | Employee</p> <p>Bob | Org1 | Employee</p> <p>Bob | Org2 | Owner</p> <p>How would I set this up in my models (has_many, through =>?) and also so that when I have an edit form, I'm able to update the user information, their Organizations and Roles all from within the same form? Note: Not sure it pertinent, but I only intend to allow those that are owners to edit their Organization.</p> <p>Thanks again!</p> <p><strong>EDIT</strong> Below is what I've got, plus an error I now receive:</p> <p>models/user.rb</p> <pre><code>class User &lt; ActiveRecord::Base has_many :org_roles has_many :orgs, :through =&gt; :org_roles accepts_nested_attributes_for :orgs, :allow_destroy =&gt; true has_one :user_detail has_one :user_address attr_accessible :orgs end </code></pre> <p>models/org.rb</p> <pre><code>class Org &lt; ActiveRecord::Base end </code></pre> <p>models/role.rb</p> <pre><code>class Role &lt; ActiveRecord::Base end </code></pre> <p>models/org_role.rb</p> <pre><code>class OrgRole &lt; ActiveRecord::Base belongs_to :user belongs_to :org belongs_to :role validates_presence_of :user, :org, :role validates_uniqueness_of :org_id, :scope =&gt; :user_id end </code></pre> <p>views/edit.html.erb </p> <pre><code> #user form info above... &lt;%=f.fields_for :orgs do |ff| %&gt; &lt;div&gt;Your Organization Name:&lt;br /&gt; &lt;%= ff.text_field :name%&gt;&lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Error Message:</p> <pre><code>Can't mass-assign protected attributes: orgs_attributes </code></pre> <p>SOLVED:</p> <p>Added :orgs_attributes to my user model, attr_accessible</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload