Note that there are some explanatory texts on larger screens.

plurals
  1. POrails - polymorphic association - one-to-one - Form is submiting nested fields with wrong name
    text
    copied!<p>I have User, which can be one of three types: Admin, Student, Teacher. Everyone has other attributes. I am trying polymorphic association one-to-one like this: </p> <p><strong>User</strong></p> <pre><code>class User &lt; ActiveRecord::Base belongs_to :identity, :polymorphic =&gt; true accepts_nested_attributes_for :identity, :allow_destroy =&gt; true attr_accessible :email, :login, :remember_token, :password_confirmation, :password, :role end </code></pre> <p><strong>Student</strong></p> <pre><code>class Student &lt; ActiveRecord::Base attr_accessible :field has_one :user, :as =&gt; :identity end </code></pre> <p><strong>Controller</strong></p> <pre><code>def new @user = User.new end def create @user = User.new(params[:user]) # It fails here. @user.identita.build ... end </code></pre> <p><strong>View</strong></p> <pre><code>&lt;%= form_for(@user) do |f| %&gt; &lt;%= f.label :login %&gt;&lt;br /&gt; &lt;%= f.text_field :login %&gt; &lt;%= f.fields_for [:identity, Student.new] do |i| %&gt; &lt;%= i.label :field %&gt;&lt;br /&gt; &lt;%= i.textfield_select :field %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>When I submit this view (more complex, but this is the core), it sends hash like this: </p> <pre><code>{"utf8"=&gt;"✓", "authenticity_token"=&gt;"...", "user"=&gt;{"login"=&gt;"...", "student"=&gt; {"field"=&gt;"..."} } </code></pre> <p>So it fails on marked line in controller with:</p> <pre><code>ActiveModel::MassAssignmentSecurity::Error in UsersController#create Can't mass-assign protected attributes: student </code></pre> <p>What am I doing wrong? Something like :as=>"student" or twisting the realationship?</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