Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 4, Devise & Polymorphic Associations
    text
    copied!<p>Here's my functioning code to register a type of user called mentor via a Rails 4 JSON API. </p> <p>Now I'm wondering, is there a better way to go about this? A more cleaner/simpler approach where Rails can automagically create the user/mentor association. </p> <p>Currently I'm setting it manually in the <code>create</code> method which doesn't seem right. So I just want to make sure there is no better way out there of going about this.</p> <p><strong>models/user.rb</strong></p> <pre><code>class User &lt; ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable belongs_to :role, :polymorphic =&gt; true end </code></pre> <p><strong>models/mentor.rb</strong></p> <pre><code>class Mentor &lt; ActiveRecord::Base has_one :user, as: :role accepts_nested_attributes_for :user end </code></pre> <p><strong>controllers/api/V1/mentors_controller.rb</strong></p> <pre><code>class Api::V1::MentorsController &lt; ApplicationController respond_to :json def create @user = User.new(user_params) @mentor = Mentor.new(mentor_params) @user.role = @mentor @user.save! @mentor.user_id = @user.id @mentor.save! respond_with :api, @mentor end private def mentor_params params.require(:mentor).permit(:first_name, :last_name) end def user_params params.require(:user).permit(:email, :password) end end </code></pre> <p><strong>UPDATE - 10/01/2013</strong></p> <p>I make some more inroads with this. Here's what I have now:</p> <p><strong>controllers/api/V1/mentors_controller.rb</strong></p> <pre><code>class Api::V1::MentorsController &lt; ApplicationController respond_to :json def create @mentor = Mentor.new(mentor_params) @mentor.user.save! @mentor.user_id = @mentor.user.id @mentor.save! respond_with :api, @mentor end private def mentor_params params.require(:mentor).permit(:first_name, :last_name, user_attributes: [:email, :password]) end end </code></pre> <p>But I still have to set the user_id manually. Only doing <code>Mentor.create(mentor_params)</code> fails to set the user_id. Any way to get around that?</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