0

重複の可能性:
Rails でデフォルト値を設定する正しい方法

2 つのデータ テーブルがあります。

1) ユーザー

2) プロファイル (フィールド user_id を持つ)

それらは次の方法で関連付けられています。

  • ユーザー has_one プロファイル
  • プロファイルの所属先ユーザー

新しいユーザーを作成するたびにプロファイル テーブルにデフォルト値を保存する可能性はありますか?

ご協力いただきありがとうございます!

4

2 に答える 2

1

ActiveRecordコールバックを使用してデフォルト プロファイルを作成できます。

メソッドを作成し、それを :after_create として使用するだけです

class User < ActiveRecord::Base

  has_one :profile

  after_create :create_default_profile

  def create_default_profile
    profile = build_profile
    # set parameters
    profile.save
  end

end

build_profile は Profile のインスタンスを構築してリンクしますが、保存はしません。create_profile も同じですが、オブジェクトも保存します。完全な説明については、ActiveRecord のドキュメントを参照してください。

build_ と create_profile の両方に属性をハッシュとして追加できるため、おそらく create_default_profile を 1 行に減らすことができます。

def create_default_profile
  profile = create_profile :some => 'attirbute', :to => 'set'
end
于 2013-01-18T19:10:15.277 に答える
0

はい、プロファイルのデフォルト値を追加できます。

ユーザーのプロファイルの値member_standingと属性を設定しています。points

ユーザーコントローラーの作成アクションで

def create
  @user = User.new(params[:user])
  profile = @user.profiles.build(:member_standing => "satisfactory", :points => 0)
  if @user.save
    redirect_to @user
  else
    render "new"
  end
end
于 2013-01-18T19:11:19.147 に答える