2013-09-30 35 views
0

這是我的函數代碼,通過Rails 4 JSON API註冊一個名爲mentor的用戶類型。Rails 4,Devise&Polymorphic Associations

現在我想知道,有沒有更好的方法去解決這個問題? Rails可以自動創建用戶/指導者關聯的更清潔/更簡單的方法。

目前我在create方法手動設置它看起來不正確。所以我只想確保沒有更好的方法去解決這個問題。

模型/ user.rb

class User < 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 => true 
end 

模型/ mentor.rb

class Mentor < ActiveRecord::Base 
    has_one :user, as: :role 
    accepts_nested_attributes_for :user 
end 

控制器/ API/V1/mentors_controller.rb

class Api::V1::MentorsController < 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 

UPDATE - 2013年10月1日

我對此做了一些更多的介入。這是我現在有:

控制器/ API/V1/mentors_controller.rb

class Api::V1::MentorsController < 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 

但我還是要手動設置USER_ID。只做Mentor.create(mentor_params)未能設置user_id。任何方式來解決這個問題?

+0

有你試圖在用戶中做一個'mentor ='方法? Rails應該使用params [:user] [:mentor]並將其傳遞給'mentor ='方法。然後你可以建立你的Mentor.new並在你的用戶類中做所有其他的事情。你的控制器應該變成'@user = User.new(user_params)''@ user.save!''respond_with:api,@ user.mentor'。 – jeremywoertink

+0

@jeremywoertink我不想把所有東西放在一個用戶控制器中。我將有幾個不同的用戶類型與不同的領域。所以我寧願把邏輯分成他們自己的控制器。 – jesal

回答

1

這是我的頭頂,但基本的想法是這樣的。

與嵌套資源

form_for @mentor do |f| 
    f.input :mentor_val 
    f.fields_for :user do |m| 
    m.input :user_val 

應該張貼params對象與格式像這樣創建一個表單:

mentor: { 
    mentor_val: 'blah' 
    user_attributes: { 
    user_val: 'foo' 
    } 
} 

現在既然已包含在你的導師模式,Rails的accepts_nested_attributes_for自動將user_attributes=方法添加到Mentor,這將構建用戶模型,包括設置關係。這意味着要創建兩個模型,所有你需要在控制器做的就是呼叫

@mentor.create(params) 
+0

我實際上嘗試過這種方法,但它完全忽略了用戶參數,並沒有在兩者之間建立任何關聯。與[此人]類似的經歷(http://stackoverflow.com/questions/18666007/devise-polymorphic-association-nested-attributes-with-simple-form-using-rails-4/18704223#18704223)。 – jesal

+0

我意識到我在請求中指定了錯誤的屬性。所以你的建議工作,但只有部分(見上文)。 – jesal

1

爲了回答您的更新問題,嘗試添加ID到您的PARAMS白名單:

def mentor_params 
    params.require(:mentor).permit(:first_name, :last_name,user_attributes: [:id, :email, :password]) 
end