2016-08-14 7 views
0

私はユーザーモデルと各ユーザーhas_oneプロファイルモデルを持っています。私はプロファイルモデルを更新したい。しかし、Userモデル(first_nameとlast_name)には2つの属性しかありません。だから私はaccepts_nested_attributes_forを使った。 更新は別のコントローラからネストされた属性としてユーザー属性を作成します

  • パスワードは空白にすることはできません

    1. メールが空白にすることはできません私のコードを

  • を以下:私は更新アクションを呼び出すとき

    、私は、プロファイルモデルに次のエラーを受け取ります:

    ユーザーモデル:

    class User < ActiveRecord::Base 
        devise :database_authenticatable, :registerable, 
        :recoverable, :rememberable, :trackable, :validatable, 
        :confirmable 
        has_one :profile 
    end 
    

    プロファイルモデル:

    class Profile < ActiveRecord::Base 
    belongs_to :user 
    accepts_nested_attributes_for :user 
    end 
    

    プロフィールコントローラ - 更新アクション

    class ProfilesController < ApplicationController 
        def profile_params 
         params.require(:profile).permit(:current_city_id, :current_country_id, :google_plus_page_url, :linkedin_page_url, :facebook_page_url, :skype_id, :user_attributes => [:first_name, :last_name]) 
        end 
        def update 
        @profile = Profile.find_by_id(params[:profile_id]) 
        respond_to do |format| 
         if @profile.update(profile_params) 
          format.json { render :show, status: :ok, location: @profile } 
         else 
          format.json { render json: @profile.errors, status: :unprocessable_entity } 
         end 
        end 
        end 
    end 
    

    だから、どのように私は、電子メール&パスワードなしでユーザーのネストされた属性を持つプロファイルを更新することができます(プロファイルコントローラではありませんデマンドコントローラー)?私は更新アクションを呼び出すとき

    答えて

    1

    は、私がプロファイルに モデル次のエラーを受け取る:

  • パスワードは空白にすることはできません

    • 電子メールが空白にすることはできませんが
  • devise検証が行われるように見えます。

    使用モデルから:validatableを削除します。

    class User < ActiveRecord::Base 
        devise :database_authenticatable, :registerable, 
        :recoverable, :rememberable, :trackable, :confirmable 
        has_one :profile 
    end 
    

    それとも賢く何かにこの検証を変更するだけon: :createを言います。

    class User < ActiveRecord::Base 
        devise :database_authenticatable, :registerable, 
        :recoverable, :rememberable, :trackable, :confirmable 
        has_one :profile 
        validates :email, presence: true, email: true, on: :create 
        validates :password, presence: true, on: :create 
    end 
    
    +0

    'validates_format_of:電子メール、と:考案:: email_regexp、allow_blank:true'を –

    -2

    私はaccepts_attributes_forUserモデルの代わりに、Profileモデルになるべきだと考えています。

    Userモデル

    class User < ActiveRecord::Base 
        devise :database_authenticatable, :registerable, 
        :recoverable, :rememberable, :trackable, :validatable, 
        :confirmable 
        has_one :profile 
        accepts_nested_attributes_for :profile 
    end 
    

    この回答を実現するためのプロファイルモデル

    class Profile < ActiveRecord::Base 
        belongs_to :user 
    end 
    
    関連する問題