0

Rails 3 で after_initialize を使用して、誰かの最初の投稿を自動的に作成しようとしています。モデルにデフォルト値を設定しましたが、ユーザーが作成されると、最初の投稿が作成されることを望んでいます。そのため、default_values だけでなく、ID が 1 の Post エントリがあります。

モデル:

class Etho < ActiveRecord::Base
belongs_to :user
attr_accessible :word_one, :word_two, :word_three, :word_four, :tagline
after_initialize :default_values

private
 def default_values
  self.word_one   ||= "Adventagious"
  self.word_two   ||= "Funny"
  self.word_three ||= "Multidisciplined"
  self.tagline    ||= "Shares the same visions as JFK. Wants to see the world fortune in prosperity."
 end

end
4

2 に答える 2

0

理解した。コントローラー内にビルドできることを忘れていました。そのため、移行に :default があり、次に User create メソッドでビルドを行います。

移行の内部:

add_column :ethos, :tagline, :text, :default => 'Shares a birthday with JFK. Believes in prosperty amongst humans.'

User の create メソッド内

ethos = @user.ethos.build

助けてくれてありがとうクリス・デューシング!

于 2012-07-08T16:30:37.803 に答える
0

コールバックメソッド「after_save」を使用するだけです

class Etho < ActiveRecord::Base belongs_to :user attr_accessible :word_one, :word_two, :word_three, :word_four, :tagline after_save :default_values

private
 def default_values
  self.word_one   ||= "Adventagious"
  self.word_two   ||= "Funny"
  self.word_three ||= "Multidisciplined"
  self.tagline    ||= "Shares the same visions as JFK. Wants to see the world fortune in prosperity."
 end

end
于 2012-07-14T11:59:09.377 に答える