這是我的函數代碼,通過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。任何方式來解決這個問題?
有你試圖在用戶中做一個'mentor ='方法? Rails應該使用params [:user] [:mentor]並將其傳遞給'mentor ='方法。然後你可以建立你的Mentor.new並在你的用戶類中做所有其他的事情。你的控制器應該變成'@user = User.new(user_params)''@ user.save!''respond_with:api,@ user.mentor'。 – jeremywoertink
@jeremywoertink我不想把所有東西放在一個用戶控制器中。我將有幾個不同的用戶類型與不同的領域。所以我寧願把邏輯分成他們自己的控制器。 – jesal