0

これは、Rails 4 JSON API を介してメンターと呼ばれるタイプのユーザーを登録する機能コードです。

今思うのですが、何か良い方法はないでしょうか?Railsがユーザー/メンターの関連付けを自動的に作成できる、よりクリーンでシンプルなアプローチ。

create現在、正しくないように思われる方法で手動で設定しています。ですから、これ以上の方法がないことを確認したいだけです。

models/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

models/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

更新 - 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 の設定に失敗します。それを回避する方法はありますか?

4

2 に答える 2

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'
  }
}

accepts_nested_attributes_forMentor モデルに含めたので、Railsは、関係の設定を含め、ユーザー モデルを構築するuser_attributes=メソッドを自動的に追加しました。Mentorこれは、両方のモデルを作成するために、コントローラーで行う必要があるのは呼び出しだけであることを意味します

@mentor.create(params)
于 2013-09-30T22:30:58.380 に答える